多线程交替打印(奇偶 / 0102…)
synchronized解决
public class EvenOdd {
public static void main(String[] args) {
EvenOddPrint evenOdd = new EvenOddPrint();
new Thread(() -> {
try {
evenOdd.evenPrint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "evenPrint").start();
new Thread(() -> {
try {
evenOdd.oddPrint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "oddPrint").start();
}
}
class EvenOddPrint {
private int i = 0;
public synchronized void evenPrint() throws InterruptedException {
while (i < 100) {
if (i % 2 == 0) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + "---> " + i);
i += 1;
this.notifyAll();
}
}
public synchronized void oddPrint() throws InterruptedException {
while (i <= 100) {
if (i % 2 != 0) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + " ---> " + i);
i += 1;
this.notifyAll();
}
}
}
三个线程打印01020304…
synchronized不能唤醒指定线程,采用juc.Lock
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ZeroOneTwo {
public static void main(String[] args) {
ZeroOneTwoPrint print = new ZeroOneTwoPrint();
new Thread(() -> {
try {
print.zeroPrint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "zero").start();
new Thread(() -> {
try {
print.evenPrint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "even").start();
new Thread(() -> {
try {
print.oddPrint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "odd").start();
}
}
class ZeroOneTwoPrint {
private int i = 1;
private int flag = 0;
private static final int MAX_NUM = 100;
private Lock lock = new ReentrantLock();
private Condition condition0 = lock.newCondition();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
public void zeroPrint() throws InterruptedException {
lock.lock();
try {
while (i < MAX_NUM) {
while (flag != 0) {
condition0.await();
}
System.out.println(Thread.currentThread().getName() + " ---> " + 0);
flag = 1;
if (i % 2 != 0) {
condition1.signal();
} else {
condition2.signal();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void evenPrint() throws InterruptedException {
lock.lock();
try {
while (i < MAX_NUM) {
while (i % 2 == 0) {
condition1.await();
}
System.out.println(Thread.currentThread().getName() + " ---> " + i);
i ++;
flag = 0;
condition0.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void oddPrint() throws InterruptedException {
lock.lock();
try {
while (i < MAX_NUM) {
while (i % 2 != 0) {
condition2.await();
}
System.out.println(Thread.currentThread().getName() + " ---> " + i);
i ++;
flag = 0;
condition0.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}