Java多執行緒交替列印
阿新 • • 發佈:2022-04-09
1. synchronized實現雙執行緒交替列印
class Print implements Runnable{ static int i=0; static final int n=100; @Override public void run() { synchronized (this) { while (i < n) { System.out.println(i++ + Thread.currentThread().getName()); notify(); try { Thread.sleep(5); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public class Main { public static void main(String[] args){ Print p=new Print(); Thread t1=new Thread(p); Thread t2=new Thread(p); t1.setName("A===="); t2.setName("B"); t1.start(); t2.start(); } }
2. 訊號量實現雙執行緒交替列印
public static void main(String[] args){ final AtomicInteger i=new AtomicInteger(0); final int n=100; final Semaphore x1=new Semaphore(1); final Semaphore x2=new Semaphore(0); new Thread(()->{ while (i.get() < n) { x1.acquireUninterruptibly(); System.out.println(i.getAndIncrement()+":A====="); x2.release(); } }).start(); new Thread(()->{ while (i.get() < n) { x2.acquireUninterruptibly(); System.out.println(i.getAndIncrement()+":B"); x1.release(); } }).start(); }