Java多线程、进度条实现赛马实验

赛马

下周一就要去做java实验了,还记得上一次实验还有一个程序没写完,匆匆交了实验报告的半成品(希望老师没发现www)。为了下周一能有更充裕的时间在实验课写代码,我搜了一下我们学校的实验报告。嘿,宁猜怎么着!还真有16年的实验报告。虽然有点不太一样,但题目大多是相同的,于是我就开始写。
这是有关赛马的一个程序,题目如下:编写一个多线程的控制程序,称为赛马程序。创建分别代表两匹马的两个线程,并将它们设置为高低不同的优先级,并以进度条的形式显示赛马过程。
以下是我经过多方学习写出的代码,希望大佬斧正。
(文章写得有点随意,毕竟我也是个随便的人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号马!");
	}
}

猜你喜欢

转载自blog.csdn.net/shallwecen/article/details/109411379