join方法

来源:互联网 发布:变声软件怎么实现 编辑:程序博客网 时间:2024/05/22 07:07
public class TestJoin {
public static void main(String[] args) {
MyThread my = new MyThread("wow");
my.start();
try
{
my.join();           //调用join方法,让两个线程变成单线程,此时要等my的run方法执行完,
}                        //再继续执行main方法
catch (InterruptedException e1){
}
for(int i=1;i<=10;i++) {
System.out.println("i am main thread");
}
}
}


class MyThread extends Thread {
MyThread(String s) {                //新线程名
super(s);
}
public void run() {
for(int i=1; i <= 10; i++ ) {
System.out.println("i am " + getName());        //getName返回该线程名字
try
{
sleep(1000);       //休息一秒
}
catch (InterruptedException e)
{
System.out.println("被打断");
break;
}
}
}
}
/*
输出10个i am wow
最后才输出i am main thread
*/
0 0
原创粉丝点击