java两个线程交替执行
时间: 2024-05-12 07:11:24 浏览: 155
java基础教程301集287 两个线程交替打印.mp4
在Java中,可以使用wait()和notify()方法实现两个线程交替执行。具体实现方法如下:
首先,定义一个共享的对象作为锁:
```java
Object lock = new Object();
```
然后,定义两个线程类,分别为奇数线程和偶数线程:
```java
class OddThread implements Runnable {
private Object lock;
public OddThread(Object lock) {
this.lock = lock;
}
public void run() {
for (int i = 1; i <= 100; i += 2) {
synchronized (lock) {
System.out.println("OddThread: " + i);
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class EvenThread implements Runnable {
private Object lock;
public EvenThread(Object lock) {
this.lock = lock;
}
public void run() {
for (int i = 2; i <= 100; i += 2) {
synchronized (lock) {
System.out.println("EvenThread: " + i);
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
```
在奇数线程中,先输出奇数,然后调用notify()方法通知偶数线程继续执行,再调用wait()方法让自己进入等待状态。在偶数线程中,先输出偶数,然后调用notify()方法通知奇数线程继续执行,再调用wait()方法让自己进入等待状态。
最后,在main函数中创建两个线程对象,并启动它们:
```java
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(new OddThread(lock));
Thread t2 = new Thread(new EvenThread(lock));
t1.start();
t2.start();
}
```
这样,就可以实现两个线程交替执行了。
阅读全文