线程之龟兔赛跑

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();
		 
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值