思路1 :用一个变量记录属于哪个线程执行,然后另外一个线程阻塞掉即可。
public class main { static volatile int a = 1; public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { for(int i = 0 ; i < 26 ; i++){ while(a % 2 == 1){ try { Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); } } System.out.println(a/2); a = a+1; } } }).start(); new Thread(new Runnable() { @Override public void run() { for(int i = 0 ; i < 26 ; i++){ while(a % 2 == 0){ try { Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); } } System.out.println((char)((a/2)+‘A‘)); a = a+1; } } }).start(); } }
思路2 :使用LockSupport中的unpark和park方法唤醒对方线程并阻塞当前线程。
import java.util.concurrent.locks.LockSupport; public class Test_LockSupport { static Thread t1 = null,t2 = null; public static void main(String[] args) { char []aI = "123456789".toCharArray(); char []aC = "ABCDEFJHI".toCharArray(); t1 = new Thread(()->{ for (char c : aI) { System.out.println(c); LockSupport.unpark(t2);//唤醒t2 LockSupport.park();//阻塞t1 } },"t1"); t2 = new Thread(()->{ for (char c : aC) { System.out.println(c); LockSupport.unpark(t1);//唤醒t1 LockSupport.park();//阻塞t2 } },"t2"); t1.start(); t2.start(); } }
两个线程,一个输出字母一个输出数字,输出A1B2C3....Z26
原文:https://www.cnblogs.com/Esquecer/p/12517220.html