一 問題概述
線程或者進程之間有兩種關系 同步和互斥,我們通常實現同步方法是使用線程的等待喚醒機制,而等待喚醒機制的使用是建立在互斥的繼承上的。但是同步線程並不一定是必須要實現互斥的。比如一個線程打印A,一個線程打印B。這兩個線程就沒有互斥關系,但是提出這么個需求:交替打印A、B 。我們一般的解決方案,往往要使用wait()/notify機制。
二 LockSupport 介紹
LockSupport作為一個工具類,主要學習它的方法。
park():在線程內調用,表示當前線程自我阻塞,直到獲得許可證
park(線程變量):讓指定的線程獲得許可證。
一看這兩個方法的定義,顯然可以利用這兩個方法實現線程的順序調用(同步)
三 兩種思路實現交替打印A/B
等待喚醒機制:
/** * @program: test * @description: 交替打印A/B 等待喚醒機制 * @author: * @create: 2019-07-22 14:28 */ public class Test3 { static class MyRun implements Runnable { static int i = 0; @Override public synchronized void run() { for (int j = 0; j < 10; j++) { if(i%2==0) System.out.println(Thread.currentThread().getName()+":A"); else System.out.println(Thread.currentThread().getName()+":B"); i++; this.notifyAll(); try { if(i>=19) Thread.sleep(10); else this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { MyRun myRun = new MyRun(); Thread a = new Thread(myRun); Thread b = new Thread(myRun); a.start(); b.start(); } }
LockSupport 實現
/** * @program: test * @description:交替打印A,B LockSupport實現 * @author: * @create: 2019-07-22 14:03 */ public class Test2 { static Thread a=null; static Thread b=null; public static void main(String[] args) { a= new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { LockSupport.park(); System.out.println(Thread.currentThread().getName()+":B"); LockSupport.unpark(b); } } }); b=new Thread((new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+":A"); LockSupport.unpark(a); LockSupport.park(); } } })); a.start(); b.start(); } }