/**
* 两个线程,一个线程输出1,一个线程输出2,
*
* @author ffr@cnic.cn
*
*/
public class SleepAndWaitThread2 {
public static void main(String[] args) {
OneThread one = new OneThread();
TwoThread two = new TwoThread();
one.start();
two.start();
}
}
class OneThread extends Thread {
@Override
public void run() {
synchronized (SleepAndWaitThread2.class) {
while (true) {
System.out.println("1");
try {
SleepAndWaitThread2.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
SleepAndWaitThread2.class.notify();
}
}
}
}
class TwoThread extends Thread {
@Override
public void run() {
synchronized (SleepAndWaitThread2.class) {
while (true) {
System.out.println("2");
SleepAndWaitThread2.class.notify();
try {
SleepAndWaitThread2.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
两个线程,一个线程输出1,一个线程输出2,循环输出
最新推荐文章于 2023-01-03 10:47:39 发布
本文介绍了一个使用Java实现的简单线程交互案例。案例中定义了两个线程,一个线程负责输出数字1,另一个线程负责输出数字2,通过wait()和notify()方法实现了线程间的同步与交替输出。
1580

被折叠的 条评论
为什么被折叠?



