Thread类
class MyThreadTest extends Thread{
public MyThreadTest(String str){
super(str);
}
public void run()
{
for (int i = 1; i <=5; i++)
{
System.out.println(" "+getName()+" run "+ i +" time");
try{
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e){
}
}
System.out.println(" "+getName()+ " DONE! ");
}
public static void main(String args[] ){
MyThreadTest mt1=new MyThreadTest("test1");
MyThreadTest mt2=new MyThreadTest("test2");
mt1.start();
mt2.start();
for(int i=1;i<=5;i++){
System.out.println(" "+Thread.currentThread().getName()+" run "+ i +" time ");
try{
sleep((int)(Math.random() * 2000));
} catch(InterruptedException e){
}
}
System.out.println(" "+Thread.currentThread().getName()+" DONE! ");
}
}
Runnable类
public class MyRunnableTest implements Runnable
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println(" "+Thread.currentThread().getName()+" run "+ i +" time");
try
{
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e){
}
}
System.out.println(" "+Thread.currentThread().getName()+ " DONE! ");
}
public static void main(String args[])
{
MyRunnableTest t1=new MyRunnableTest();
MyRunnableTest t2=new MyRunnableTest();
Thread=new Thread(t1,"test1");
Thread=new Thread(t2,"test2");
test1.start();
test2.start();
for (int i = 1; i <=5; i++)
{
System.out.println(Thread.currentThread().getName()+" run "+ i +" time");
try{
Thread.sleep((int)(Math.random() * 1000));
} catch (InterruptedException e){
}
}
System.out.println(Thread.currentThread().getName()+ " DONE! ");
}
}