两个线程交替打印数字
好久没写这个东西了,有点忘了,本来想百度一下偷个懒得的,但是网上发现尽是类似方案A,
但是我觉得方案A有点弊端,o.notify 是随机的,不能100%保证完全的顺序,所以我写了一下PlanB方便自己偷懒,也方便大家学习使用。
方案A:
package com.exam.spring.demo;
public class PrintA {
private static Object o = new Object();
static class A extends Thread {
@Override
public synchronized void run() {
synchronized (o) {
for (int i = 0; i < 100; i = i + 2) {
System.out.println("A" + i);
try {
o.wait();
o.notify();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
static class B extends Thread {
@Override
public void run() {
synchronized (o) {
for (int i = 1; i < 100; i = i + 2) {
System.out.println("B" + i);
try {
o.notify();
o.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
public static void main(String[] args) {
Thread A = new A();
Thread B = new B();
// B.join();
A.start();
B.start();
}
}
方案B:
package com.exam.spring.demo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class PrintB {
private static Lock lockA = new ReentrantLock();
private static Condition conditionA = lockA.newCondition();
private static Condition conditionB = lockA.newCondition();
static class A extends Thread {
@Override
public void run() {
lockA.lock();
try {
for (int i = 0; i < 10; i = i + 2) {
System.out.println("A" + i);
conditionB.signal();
conditionA.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lockA.unlock();
}
}
}
static class B extends Thread {
@Override
public void run() {
lockA.lock();
try {
for (int i = 1; i < 10; i = i + 2) {
System.out.println("B" + i);
conditionA.signal();
conditionB.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lockA.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread A = new A();
Thread B = new B();
// 保证一定先是A
A.join();
A.start();
B.start();
}
}