线程之龟兔赛跑

来源:互联网 发布:js正则验证非负正整数 编辑:程序博客网 时间:2024/05/05 16:39
import java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextArea;public class RaceFrame extends JFrame{JTextArea t1,t2;JButton b;public RaceFrame(){t1=new JTextArea("兔子的成绩");t2=new JTextArea("乌龟的成绩");getContentPane().add(t1,BorderLayout.WEST);getContentPane().add(t2,BorderLayout.EAST);b=new JButton("比赛开始");b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { Rabbit r=new RaceFrame().new Rabbit(); Thread th1=new Thread(r,"兔子"); Wugui w=new RaceFrame().new Wugui();  Thread th2=new Thread(w,"乌龟"); th2.start();th1.start();} });JPanel p=new JPanel();//创建面板p.add(b);getContentPane().add(p,BorderLayout.SOUTH);setVisible(true);setBounds(100,100,500,500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}private class Rabbit implements Runnable{public void run(){for(int i=1;i<11;i++){//模拟10次赛跑过程String text=t1.getText();//获得文本域信息try{Thread.sleep(1);//线程休眠}catch(Exception e){e.printStackTrace();}t1.setText(text+"兔子跑了"+i+"0米\n");if(i==9){t1.setText(text+"兔子在睡觉\n");try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}}if(i==10){try{Thread.sleep(1);}catch(InterruptedException e){e.printStackTrace();}t1.setText(text+"兔子到达终点");}}}}private class Wugui implements Runnable{public void run(){for(int i=0;i<11;i++){String text2=t2.getText();//获得文本域信息t2.setText(text2+"乌龟跑了"+i+"0米\n");if(i==10){t2.setText(text2+"乌龟到达终点了");}}}}public static void main(String[] args) {  /* Wugui w=new RaceFrame().new Wugui();  Thread th2=new Thread(w,"乌龟");  th2.start();*/RaceFrame f=new RaceFrame(); }}

原创粉丝点击