Java中控制线程执行顺序的小技巧:join
假设有三个线程,threadone,threadtwo,threadthree
如何保证线程按照1---->2---->3的顺序进行执行呢?
1 package com.itheima.com; 2 3 public class ThreadOne implements Runnable{ 4 5 @Override 6 public void run() { 7 String threadName = Thread.currentThread().getName(); 8 9 System.out.println(threadName+"start..."); 10 11 System.out.println(threadName+"end..."); 12 13 } 14 15 }
1 package com.itheima.com; 2 3 public class ThreadTwo implements Runnable { 4 5 @Override 6 public void run() { 7 String ThreadName = Thread.currentThread().getName(); 8 System.out.println(ThreadName+"start..."); 9 10 System.out.println(ThreadName+"end..."); 11 12 } 13 14 }
1 package com.itheima.com; 2 3 public class ThreadThree implements Runnable { 4 5 @Override 6 public void run() { 7 String ThreadName = Thread.currentThread().getName(); 8 System.out.println(ThreadName+"start..."); 9 10 System.out.println(ThreadName+"end..."); 11 12 } 13 14 }
然后定义一个类,再类中按顺序调用三个线程
1 package com.itheima.com; 2 3 public class JoinMainTest { 4 public static void main(String[] args) { 5 String ThreadName = Thread.currentThread().getName(); 6 System.err.println(ThreadName+"start..."); 7 8 Thread thread1 = new Thread(new ThreadOne()); 9 Thread thread2 = new Thread(new ThreadTwo()); 10 Thread thread3 = new Thread(new ThreadThree()); 11 12 thread1.start(); 13 thread2.start(); 14 thread3.start(); 15 System.out.println(ThreadName+"end..."); 16 } 17 }
然而运行结果如下:
1 mainstart... 2 mainend... 3 Thread-0start... 4 Thread-0end... 5 Thread-1start... 6 Thread-2start... 7 Thread-2end... 8 Thread-1end...
发现并没有按照1,2,3的顺序进行执行
这是因为java中线程的执行顺序是一种竞争关系,谁先抢到了执行资格,谁就可以执行
那么如何实现呢?
1 package com.itheima.com; 2 3 public class JoinMainTest2 { 4 public static void main(String[] args) { 5 String threadName = Thread.currentThread().getName(); 6 7 System.out.println(threadName+"start..."); 8 9 Thread thread1 = new Thread(new ThreadOne()); 10 Thread thread2 = new Thread(new ThreadTwo()); 11 Thread thread3 = new Thread(new ThreadThree()); 12 13 try { 14 thread1.start(); 15 thread1.join(); 16 thread2.start(); 17 thread2.join(); 18 thread3.join(); 19 thread3.start(); 20 } catch (Exception e) { 21 System.out.println("thread join Exception"); 22 } 23 System.out.println(threadName+"end..."); 24 25 } 26 }
打印结果如下 :
1 mainstart... 2 Thread-0start... 3 Thread-0end... 4 Thread-1start... 5 Thread-1end... 6 mainend... 7 Thread-2start... 8 Thread-2end...
使用了join这个方法,这是因为join的底层,其实是wait
1 public final synchronized void join(long millis) 2 throws InterruptedException { 3 long base = System.currentTimeMillis(); 4 long now = 0; 5 6 if (millis < 0) { 7 throw new IllegalArgumentException("timeout value is negative"); 8 } 9 10 if (millis == 0) { 11 while (isAlive()) { 12 wait(0); 13 } 14 } else { 15 while (isAlive()) { 16 long delay = millis - now; 17 if (delay <= 0) { 18 break; 19 } 20 wait(delay); 21 now = System.currentTimeMillis() - base; 22 } 23 } 24 }

浙公网安备 33010602011771号