我正在学习Java的多线程,现在正在尝试:
我想要两个线程,线程A只打印奇数,线程B只打印偶数。
当线程A完成输出数字时,它告诉B:“轮到你打印”,反之亦然。在C ++中,我使用信号量来做这些事情,但我不知道如何用Java做这件事。
这是我的代码:
class printer {
int i;
void say() {
System.out.println(i++);
}
}
class p1 extends printer implements Runnable {
public void run() {
while (true) {
//waitP2();
say();
//tellP2();
try {
Thread.sleep(1);
} catch (InterruptedException e) {}
}
}
}
class p2 extends printer implements Runnable {
public void run() {
while (true) {
//waitP1();
say();
//tellP1();
try {
Thread.sleep(1);
} catch (InterruptedException e) {}
}
}
}
public class a {
public static void main(String[] args) {
Thread t1 = new Thread(new p1());
Thread t2 = new Thread(new p2());
t1.start(); t2.start();
try {
t1.join(); t2.join();
} catch (InterruptedException e) {}
}
}