看一下运行结果自己应该能想到嘛
t1和t2只有那个for循环的输出语句
而t1.join()是main线程调用的
所以t1和t2并发打印输出语句
等t1打印完毕后,主线程打印输出语句
如果要让t2执行t1.join(),方法也很多
提供一种:
- class Demo implements Runnable{
- Thread other=null;
- public Demo(Thread other){
- this.other=other;
- }
- public Demo(){
- }
- public void run(){
- if(other!=null)
- try{
- other.join();
- }catch(InterruptedException e){
- e.printStackTrace();
- }
- for(int x=0;x<70;x++){
- System.out.println(Thread.currentThread().getName()+"-----"+x);
- // Thread.yield();
- }
- }
- }
- public class JoinDemo{
- public static void main(String[] args) throws Exception{
- // Demo d = new Demo();
- Thread t1=new Thread(new Demo());
- Thread t2=new Thread(new Demo(t1));//t2 输出前会执行t1.join()
- t1.start();
- t2.start();
- t2.join();
- /*
- 然后main线程等待t2线程.
- 最后顺序就为t1---t2---main
- */
- for(int x=0;x<90;x++){
- System.out.println(Thread.currentThread().getName()+"---"+x);
- }
- System.out.println("over");
- }
- }
复制代码 |