Turn https://www.oschina.net/code/snippet_111708_25438
This is a classic question, the essence of my solution is to abstract the problem into the producer consumer model, but it is a special producer consumer model, there are two requirements:
1, buffer size is 1 (with a Boolean variable to represent it)
2. The buffer is initially empty
More specifically, you can think of it as a printer that can only put one sheet of paper at a time, the thread that puts the paper is a, and the thread that prints is B. The initial state printer has no paper.
// 打印机类
public
class
Printer {
private
boolean
hasBufferToPrint =
false
;
// 打印缓冲区是否有内容可以打印
// 打印A:相当于生产者,放一张纸
public
synchronized
void
printA() {
while
(hasBufferToPrint) {
// 缓冲区还有内容
try
{
wait();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(
"A"
);
hasBufferToPrint =
true
;
notify();
// 唤醒打印B的线程
}
// 打印B:相当于消费者,消耗缓冲区中的纸,打印纸张
public
synchronized
void
printB() {
while
(!hasBufferToPrint) {
try
{
wait();
}
catch
(InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(
"B"
);
hasBufferToPrint =
false
;
notify();
// 唤醒打印A的线程
}
static
class
ThreadA
extends
Thread {
private
Printer printer;
public
ThreadA(Printer printer) {
this
.printer = printer;
}
public
void
run() {
for
(
int
i =
0
; i <
10
; i++) {
printer.printA();
}
}
}
static
class
ThreadB
extends
Thread {
private
Printer printer;
public
ThreadB(Printer printer) {
this
.printer = printer;
}
public
void
run() {
for
(
int
i =
0
; i <
10
; i++) {
printer.printB();
}
}
}
public
static
void
main(String args[]) {
Printer printer =
new
Printer();
// A、B线程共享同一个打印机
Thread a =
new
ThreadA(printer);
Thread b =
new
ThreadB(printer);
a.start();
b.start();
}
}
Java Multithreading (producer consumer)