race
I'm going to do a java experiment next Monday. I still remember that there was a program that was not finished in the last experiment, and I hurriedly handed in the semi-finished product of the experiment report (hope the teacher did not find www). In order to have more time to write code in the experiment class next Monday, I searched our school's experiment report. Hey, guess what! There are really 16 years of experimental reports. Although it is a bit different, the topics are mostly the same, so I started writing.
This is a program about horse racing. The topic is as follows: Write a multi-threaded control program, called a horse racing program. Create two threads representing two horses, and set them to different priorities, and display the horse racing process in the form of a progress bar.
The following is the code I wrote after many studies, I hope the big guys are correct.
(The article is a bit casual, after all, I am also a casual person www)
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号马!");
}
}