下面程序 创建了三个子线程
public class thread {
public static void main(String args[]){
new NewThread("One");
new NewThread("Two");
new NewThread("Three");
try{
Thread.sleep(10000);
}
catch(InterruptedException e){
System.out.println("main thread interrupted");
}
System.out.println("main thread exiting");
}
}
//creat a multiple thread
class NewThread implements Runnable{
String name; //name of thread
Thread t;
NewThread(String threadname){
name=threadname;
t=new Thread(this ,name);
System.out.println("New thread :"+t);
t.start();
}
//@Override
public void run() {
// TODO Auto-generated method stub
try{
for(int i=5;i>0;i--)
{
System.out.println(name+":"+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println(name+"Interrupted");
}
System.out.println(name+"exiting");
}
}
程序运行结果如下:
New thread :Thread[One,5,main]
New thread :Thread[Two,5,main]
One:5
New thread :Thread[Three,5,main]
Three:5
Two:5
One:4
Two:4
Three:4
One:3
Two:3
Three:3
One:2
Three:2
Two:2
One:1
Two:1
Three:1
Oneexiting
Threeexiting
Twoexiting
main thread exiting
New thread :Thread[Two,5,main]
One:5
New thread :Thread[Three,5,main]
Three:5
Two:5
One:4
Two:4
Three:4
One:3
Two:3
Three:3
One:2
Three:2
Two:2
One:1
Two:1
Three:1
Oneexiting
Threeexiting
Twoexiting
main thread exiting
如上所见,一旦启动程序,所有三个子线程将共享cpu。应注意main()方法部分程序中对语句sleep(10000)的调用,这使主线程睡眠10秒,以确保它最后结束