任务四:(选作)
创建两个独立的线程,一个线程打印“A”,另一个线程打印 “B”,两个线程交替输出,输出结果为:ABABABABABAB…
提示:使用wait-notify机制协调线程
package forth;
class PA extends Thread {
private Share shared;
public PA(Share s) {
shared = s;
}
public void run() {
for (int i = 1; i < 20; i++) {
shared.put('A');
System.out.print('A');
try {
sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}
class PB extends Thread {
private Share shared;
public PB(Share s) {
shared = s;
}
public void run() {
char value = '\0';
for (int i = 1; i < 20; i++) {
value = (char) (shared.get() + 1);
System.out.print(value);
}
}
}
class Share {
private char contents;
private boolean available = false;
public synchronized char get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(char value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}
public class test4 {
public static void main(String[] args) {
Share s = new Share();
PA A = new PA(s);
PB B = new PB(s);
A.start();
B.start();
}
}