📄 example19_10.java
字号:
import java.awt.*;import java.awt.event.*;import java.applet.*;
public class Example19_10 extends Applet implements Runnable,ActionListener
{ Button b=new Button("go");TextField text=null;
Thread 发令员,运动员_1,运动员_2;
int x=10;//线程运动的起始位置。
Graphics mypen=null;
public void init()
{ b.addActionListener(this);text=new TextField(20);
发令员=new Thread(this);运动员_1=new Thread(this);运动员_2=new Thread(this);
add(b);add(text);
mypen=getGraphics();
}
public void start()
{ 发令员.start();
}
public void actionPerformed(ActionEvent e)
{ 发令员.interrupt();//点击按扭结束发令员的生命。
}
public void run()
{ if(Thread.currentThread()==发令员)
{ while(true)
{ text.setText("准备跑... ...");text.setText("......");
try { 发令员.sleep(30);
}
catch(InterruptedException e)
{ //点击按扭结束生命,并让运动员_1开始跑。
text.setText("跑");
运动员_1.start(); break;
}
}
}
if(Thread.currentThread()==运动员_1)
{ while(true)
{ x=x+1;
mypen.setColor(Color.blue);
mypen.clearRect(10,80,99,100);//显示线程运动的动画。
mypen.fillRect(x,85,5,5);
try { 运动员_1.sleep(10);
}
catch(InterruptedException e)
{ //通知运动员_2开始跑,运动员_1结束生命:
运动员_2.start(); return;
}
if(x>=100)
{ 运动员_1.interrupt();//运动员_1当跑到100米处时结束生命。
}
}
}
if(Thread.currentThread()==运动员_2)
{ while(true)
{ x=x+1;
mypen.setColor(Color.red);
mypen.clearRect(105,80,150,100);//显示线程运动的动画。
mypen.fillRect(x+5,85,7,7);
try { 运动员_2.sleep(10);
}
catch(InterruptedException e)
{text.setText("到达终点"); return;
}
if(x>=200) //运动员_2跑到200米处时结束生命。
{ 运动员_2.interrupt();
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -