[java]多執行緒順序列印
阿新 • • 發佈:2018-12-02
package com.dongshuo.test.multithread; import javafx.beans.binding.ObjectExpression; /** * @author :dongshuo * @date : 2018/11/18 18:33 * @desc : 3個執行緒交替列印 */ public class 多執行緒交替列印 { public static class ThreadPriter implements Runnable { private String name; //名字 private Object pre; //前一把鎖 private Object self; //當前鎖 public ThreadPriter(String name, Object pre, Object self) { this.name = name; this.pre = pre; this.self = self; } @Override public void run() { //列印10次 int count = 10; while (count > 0) { synchronized (pre) { synchronized (self) { //列印 System.out.print(name); count--; //喚醒其他執行緒 self.notifyAll(); } //釋放 pre鎖 try { if (count == 0) { pre.notifyAll(); } else { pre.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args)throws Exception{ Object a = new Object(); Object b = new Object(); Object c = new Object(); ThreadPriter A = new ThreadPriter("A",c,a); ThreadPriter B = new ThreadPriter("B",a,b); ThreadPriter C = new ThreadPriter("C",b,c); new Thread(A).start(); Thread.sleep(10); new Thread(B).start(); Thread.sleep(10); new Thread(C).start(); Thread.sleep(10); } }
package com.dongshuo.test.multithread; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @author :dongshuo * @date : 2018/11/18 19:01 * @desc : */ public class 可重入鎖 { private static Lock lock = new ReentrantLock(); private static int state = 0; public static class ThreadA extends Thread { @Override public void run() { for (int i = 0; i < 10; ) { try { lock.lock(); while (state % 3 == 0) { System.out.print("A"); state++; i++; } } finally { lock.unlock(); } } } } public static class ThreadB extends Thread { @Override public void run() { for (int i = 0; i < 10; ) { try { lock.lock(); while (state % 3 == 1) { System.out.print("B"); state++; i++; } } finally { lock.unlock(); } } } } public static class ThreadC extends Thread { @Override public void run() { for (int i = 0; i < 10; ) { try { lock.lock(); while (state % 3 == 2) { System.out.print("C"); state++; i++; } } finally { lock.unlock(); } } } } public static void main(String[] args) throws Exception { new ThreadA().start(); new ThreadB().start(); new ThreadC().start(); } }