賽馬
下周一就要去做java實(shí)驗(yàn)了,還記得上一次實(shí)驗(yàn)還有一個(gè)程序沒寫完,匆匆交了實(shí)驗(yàn)報(bào)告的半成品(希望老師沒發(fā)現(xiàn)www)。為了下周一能有更充裕的時(shí)間在實(shí)驗(yàn)課寫代碼,我搜了一下我們學(xué)校的實(shí)驗(yàn)報(bào)告。嘿,寧猜怎么著!還真有16年的實(shí)驗(yàn)報(bào)告。雖然有點(diǎn)不太一樣,但題目大多是相同的,于是我就開始寫。
這是有關(guān)賽馬的一個(gè)程序,題目如下:編寫一個(gè)多線程的控制程序,稱為賽馬程序。創(chuàng)建分別代表兩匹馬的兩個(gè)線程,并將它們設(shè)置為高低不同的優(yōu)先級,并以進(jìn)度條的形式顯示賽馬過程。
以下是我經(jīng)過多方學(xué)習(xí)寫出的代碼,希望大佬斧正。
import javax.swing.*;
import java.awt.*;
public class Test 
{
  static Thread threadObj1;
  static Thread threadObj2;
  JFrame frame;
  JPanel panel;
  JLabel label1,label2;
  static JLabel label3;
  static JProgressBar progressBar1;
 static JProgressBar progressBar2;
  public static void main(String[] args)
  {
   Test test=new Test();
   test.go();
    threadObj1=new ThreadClass1();
    threadObj2=new ThreadClass2();
    threadObj1.setPriority(6);
    threadObj2.setPriority(4);
    threadObj1.start();
    threadObj2.start();
  }
  void go() 
  {
    frame=new JFrame("賽馬");
    panel=new JPanel();
    panel.setLayout(new GridLayout(2,2));
    label1=new JLabel("一號馬");
    label2=new JLabel("二號馬");
    label3=new JLabel("加油!");
    progressBar1 = new JProgressBar(SwingConstants.HORIZONTAL,0,100);
    progressBar1.setStringPainted(true);
    progressBar2 = new JProgressBar(SwingConstants.HORIZONTAL,0,100);
    progressBar2.setStringPainted(true);
    panel.add(label1);
    panel.add(progressBar1);
    panel.add(label2);
    panel.add(progressBar2);
    frame.getContentPane().add(panel,BorderLayout.CENTER);
    frame.getContentPane().add(label3,BorderLayout.SOUTH);
    frame.setSize(300, 100);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}
class ThreadClass1 extends Thread
{
 public void run()
 {
  while(Test.progressBar1.getValue()<100)
  {
   Test.progressBar1.setValue(Test.progressBar1.getValue()+1);
   System.out.println(Test.progressBar1.getValue());
   try{
    Thread.sleep((int)(Math.random()*300+100));
   }catch(InterruptedException e) {}
  }
  if(Test.progressBar1.getValue()==100 && Test.progressBar2.getValue()!=100)
   Test.label3.setText("勝利者:1號馬!");
 }
}
class ThreadClass2 extends Thread
{
 public void run()
 {
  while(Test.progressBar2.getValue()<100)
  {
   Test.progressBar2.setValue(Test.progressBar2.getValue()+1);
   System.out.println(Test.progressBar2.getValue());
   try{
    Thread.sleep((int)(Math.random()*300+100));
   }catch(InterruptedException e) {}
  }
  if(Test.progressBar2.getValue()==100 && Test.progressBar1.getValue()!=100)
   Test.label3.setText("勝利者:2號馬!");
 }
}
申請創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!
 
       
      
 
             
            