class InsteadPrint {
public static class PrintABC implements Runnable {
Object obj = null;
public PrintABC(Object obj) {
this.obj = obj;
}
@Override
public void run() {
synchronized (obj) {
char ch = 'A';
for (int i = 0; i < 26; i++) {
System.err.println((char) (ch + i));
try {
obj.notifyAll();
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static class Print123 implements Runnable {
Object obj = null;
public Print123(Object obj) {
this.obj = obj;
}
@Override
public void run() {
synchronized (obj) {
for (int i = 0; i < 100; i++) {
System.err.println(i);
if (i % 2 == 1) {
try {
obj.notifyAll();
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public void test() {
Object obj = new Object();
new Thread(new Print123(obj)).start();
new Thread(new PrintABC(obj)).start();
}
}
JAVA多线程,交替打印数字字母
最新推荐文章于 2024-07-22 15:11:54 发布