用JAVA实现一个多线程,一个线程每隔500毫秒输出A,一个线程每隔500毫秒输出B。实例 : A B A B A B A B … 共输出20次
使用单例设计模式保证为一个对象 用 wait()和notifyAll()控制线程执行
代码:
package ss;
class C {
private static C c = new C();
public int state = 1;
private C() {
}
public static C getC() {
return c;
}
}
class A extends Thread {
C c = C.getC();
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (c) {
if (c.state != 1) {
try {
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
System.out.println("A");
c.state = 2;
c.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class B extends Thread {
C c = C.getC();
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (c) {
if (c.state != 2) {
try {
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
System.out.println("B");
c.state = 1;
c.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Demo {
public static void main(String[] args) {
A a = new A();
B b = new B();
a.start();
b.start();
}
}