Java赛马程序
作者:互联网
编写一个多线程的控制程序,称为赛马程序。创建分别代表两匹马的两个线程,并将它们设置为高低不同的优先级,并以进度条的形式显示赛马过程。
没几天Java要考试了,紧急学习一下再把之前参考(10条消息) Java多线程、进度条实现赛马实验_shallwecen的博客-CSDN博客做的实验自己敲敲,如有不足还请大佬们指点。
import java.awt.*;
import javax.swing.*;
public class myHourseRace{
JFrame frame;
JPanel panel;
JLabel label1,label2;
static JLabel label3;
static JProgressBar hourse1;
static JProgressBar hourse2;
static Thread a;
static Thread b1;
static Thread b2;
public static void main(String[] args){
myHourseRace myFrame = new myHourseRace();
myFrame.set();
System.out.println("战况记录");
a = new hourseRace();
a.start();
}
void set(){
frame = new JFrame("小马谷荣誉之战");
panel = new JPanel(new GridLayout(2,2));
label1 = new JLabel("云宝");
label2 = new JLabel("苹果嘉儿");
label3 = new JLabel("比赛即将开始!倒计时3");
hourse1 = new JProgressBar(SwingConstants.HORIZONTAL);
hourse1.setStringPainted(true);
hourse2 = new JProgressBar();
hourse2 = new JProgressBar(SwingConstants.HORIZONTAL);
hourse2.setStringPainted(true);
panel.add(label1);
panel.add(hourse1);
panel.add(label2);
panel.add(hourse2);
frame.getContentPane().add(panel,BorderLayout.CENTER);
frame.getContentPane().add(label3,BorderLayout.SOUTH);
frame.setSize(300,100);
frame.setVisible(true);
}
}
class hourseRace extends Thread{
public void run(){
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
myHourseRace.label3.setText("比赛即将开始!倒计时2");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
myHourseRace.label3.setText("比赛即将开始!倒计时1");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
myHourseRace.label3.setText("比赛开始!小马们加油!!!");
myHourseRace.b1 = new hourseRun(myHourseRace.hourse1);
myHourseRace.b2 = new hourseRun(myHourseRace.hourse2);
myHourseRace.b1.setPriority(6);
myHourseRace.b2.setPriority(4);
myHourseRace.b1.start();
myHourseRace.b2.start();
}
}
class hourseRun extends Thread{
JProgressBar hourse;
public hourseRun(JProgressBar hourse){
this.hourse = hourse;
}
public void run(){
while(hourse.getValue()!=100){
hourse.setValue(hourse.getValue()+1);
System.out.println(hourse.getValue());
try{
sleep((int)(Math.random()*500+100));
}catch(InterruptedException e){
e.printStackTrace();
}
}
if(myHourseRace.hourse1.getValue()==100&&myHourseRace.hourse2.getValue()!=100)
myHourseRace.label3.setText("让我们恭喜云宝获胜!");
if(myHourseRace.hourse2.getValue()==100&&myHourseRace.hourse1.getValue()!=100)
myHourseRace.label3.setText("让我们恭喜苹果嘉儿获胜!");
}
}
标签:hourse2,Java,Thread,label3,程序,new,赛马,hourse,myHourseRace 来源: https://blog.csdn.net/Sweet7weight/article/details/121293431