编写一个程序,启动三个线程,三个线程的ID分别是A,B,C * 每个线程将自己的ID值在屏幕上打印10遍,打印顺序是 * ABCAABC…
在一个类中定义三个方法,并在方法中加synchronzied关键字
class MyThread1{
int count = 1;
public synchronized void printA() { //A线程
while(count<=0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("A");
count--;
this.notifyAll();
}
public synchronized void printB() { //B线程
while(count!=0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("B");
count--;
this.notifyAll();
}
public synchronized void printC() { //C线程
while(count>=0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("C");
count=-count;
this.notifyAll();
}
}
在主类中定义三个线程,实现Runnable接口
public class ThreadDemo2 {
public static void main(String[] args) {
MyThread1 thread = new MyThread1();
new Thread(new Runnable() {
public void run() {
for(int i=0; i<10; i++) {
thread.printA();
}
}
}).start();
new Thread() {
public void run() {
for(int i=0; i<10; i++) {
thread.printB();
}
}
}.start();
new Thread(new Runnable() {
public void run() {
for(int i=0; i<10; i++) {
thread.printC();
}
}
}).start();
}
}