多執行緒--多個執行緒迴圈順序的多種實現。
阿新 • • 發佈:2019-01-27
問題:3個執行緒按順序列印ABC,A執行緒列印A,B執行緒列印B,C執行緒列印C.
實現一:使用synchronized關鍵字:
package com.Thread; import java.util.concurrent.atomic.AtomicInteger; /** * Created by Administrator on 2018/3/25 0025. */ public class Print implements Runnable { private static AtomicInteger count = new AtomicInteger(0); public static voidmain ( String args[] ) { Print p1 = new Print(); Print p2 = new Print(); Print p3 = new Print(); Thread t1 = new Thread(p1); Thread t2 = new Thread(p2); Thread t3 = new Thread(p3); t1.start(); t2.start(); t3.start(); } public void run () { while (true) { synchronized (count) { try{ if (count.get() % 3 == 0) { System.out.print("A"); } else if (count.get() % 3 == 1) { System.out.print("B"); } else { System.out.print("C"); } count.set(count.get() + 1); count.notifyAll(); count.wait(); } catch (InterruptedException e) { e.printStackTrace();} } } } }
實現二:使用重入鎖+Condition
package com.Thread; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by Administrator on 2018/3/25 0025. */ public class Print1 implements Runnable { static Lock lock = new ReentrantLock(); static Condition c1 = lock.newCondition(); static Condition c2 = lock.newCondition(); static Condition c3 = lock.newCondition(); static Integer aa=1; public static void main ( String args[] ) { new Thread(new Print1()).start(); new Thread(new Print1()).start(); new Thread(new Print1()).start(); } public void run () { for (int i = 1; i < 4; i++) { if (aa % 3 == 1) { try { lock.lock(); System.out.print("A"); ++aa; c2.signal(); c1.await(); } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } else if (aa % 3 == 2) { try { lock.lock(); System.out.print("B"); ++aa; c3.signal(); c2.await(); } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } else if (aa % 3 == 0) { try { lock.lock(); System.out.print("C"); ++aa; c1.signal(); c3.await(); } catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } } } }