package test.thread;
/**3个线程,分别打印A,B,C,循环打印ABC十次
* @author lsh
*
*/
public class TestABC {
public static void main(String[] args) throws Exception {
ABC abc = new ABC(); //多线程中用来锁住对象 操作,已实现同步功能
A a = new A(abc);
B b = new B(abc);
C c = new C(abc);
Thread tA = new Thread(a);
Thread tB = new Thread(b);
Thread tC = new Thread(c);
tC.start();
tB.start();
tA.start();
tA.join(); //等待线程完成
tB.join();
tC.join();
System.out.println("完成");
}
}
class ABC {
int i = 1; //打印ABC的标志,1打印A,2打印B,3打印C
}
/** 线程A 打印 字符A
* @author lsh
*
*/
class A implements Runnable {
ABC abc;
public A(ABC abc) {
this.abc = abc;
}
private void prin() {
synchronized (abc) {
try {
for (int i = 0; i < 10; i++) {
while (abc.i != 1) {
abc.wait(); //等待
}
System.out.print("A");
abc.i = 2;
abc.notifyAll();//释放对象锁
}
} catch (Exception e) {
e.printStackTrace();
abc.notifyAll();
}
}
}
@Override
public void run() {
prin();
}
}
/** 线程B 打印 字符B
* @author lsh
*
*/
class B implements Runnable {
ABC abc;
public B(ABC abc) {
this.abc = abc;
}
private void prin() {
synchronized (abc) {
try {
for (int i = 0; i < 10; i++) {
while (abc.i != 2) {
abc.wait();
}
System.out.print("b");
abc.i = 3;
abc.notifyAll();
}
} catch (Exception e) {
e.printStackTrace();
abc.notifyAll();
}
}
}
@Override
public void run() {
prin();
}
}
/** 线程C 打印 字符C
* @author lsh
*
*/
class C implements Runnable {
ABC abc;
public C(ABC abc) {
this.abc = abc;
}
private void prin() {
synchronized (abc) {
try {
for (int i = 0; i < 10; i++) {
while (abc.i != 3) {
abc.wait();
}
System.out.println("c"+" "+(i+1)+"次");
abc.i = 1;
abc.notifyAll();
}
} catch (Exception e) {
e.printStackTrace();
abc.notifyAll();
}
}
}
@Override
public void run() {
prin();
}
}