您的位置:首页 > 其它

多线程的一个例子

2005-12-26 23:43 489 查看
这个程序是照抄书上的例子,,《Java项目培训指南》,感觉还是很有收获,,,
import java.lang.Thread;
import java.lang.System;
import java.lang.Math;
import java.lang.InterruptedException;
public class Thread1
{
public static void main(String args[])
throws java.io.IOException
{
System.out.println("if want to show the result,press Return ");
MyThread thread1=new MyThread("thread1");
MyThread thread2=new MyThread("thread2");
thread1.start();
thread2.start();
char ch;
while ((ch=(char)System.in.read())!='/n');
thread1.tStart();
thread2.tStart();
while (thread1.isAlive()||thread2.isAlive())
{
}
System.out.println("The thread test is end.");
}
}
class MyThread extends Thread
{
private boolean keepRunning=true;
public MyThread(String id)
{
super(id);
}
void randomWait()
{
try
{
sleep((long)(3000*Math.random()));
}
catch(InterruptedException x)
{
System.out.println("Interrpted!!");
}
}
public void tStart()
{
keepRunning=false;
}
public void run()
{
int i=0;
while (keepRunning) i++;
for (int j=0;j<3;j++)
{
randomWait();
System.out.println("I am "+getName()+" - - I hava run "+i+" times.");
i++;
}
System.out.println(getName()+" is dead!");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: