1.第一种使用synchronized,notify,wait
package com.program;
public class TestThread {public static void main(String[] args) {
final Object object = new Object();
Runnable runnable = new Runnable() {
public void run() {
for (int i = 1;
i <= 5;
i++) {
synchronized (object) {
object.notify();
System.out.println(Thread.currentThread().getName() + ":" + i);
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Runnable runnable1 = new Runnable() {
public void run() {
for (int i = 6;
i <= 10;
i++) {
synchronized (object) {
object.notify();
System.out.println(Thread.currentThread().getName() + ":" + i);
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(runnable).start();
new Thread(runnable1).start();
}}
2.第二种使用Lock,condition,signal,await
package com.program;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {public static void main(String[] args) {
final Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(new Runnable() {
public void run() {
try {
for (int i = 1;
i <= 5;
i++) {
lock.lock();
condition.signal();
System.out.println(Thread.currentThread().getName() + ":" + i);
condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
executorService.execute(new Runnable() {
public void run() {
try {
for (int i = 6;
i <= 10;
i++) {
lock.lock();
condition.signal();
System.out.println(Thread.currentThread().getName() + ":" + i);
condition.await();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
}}
3.第3种使用堵塞队列结合线程使用
package com.program;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class TestBlocking {public static void main(String[] args) throws InterruptedException {
final BlockingQueue blockingQueue = new ArrayBlockingQueue(10);
final BlockingQueue blockingQueue1 = new ArrayBlockingQueue(10);
new Thread(new Runnable() {
public void run() {
for (int i = 1;
i <= 5;
i++) {
try {
blockingQueue.put(i);
System.out.println(blockingQueue1.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 6;
i <= 10;
i++) {
try {
System.out.println(blockingQueue.take());
blockingQueue1.put(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}}
【两个线程交替执行几种方式】
推荐阅读
- 代码狂魔|实战证明java中的两把锁ReentrantLock与synchronized的系统调用
- 进程通信方式
- 解决方案|大文件拆分方案的java实践
- 多线程编程(1)(共享内存与锁)
- Java|多线程编程(二)——面试题,每个线程只打印一种字符,多个线程协同顺序打印n次字符串(求大神的其他实现方案)
- 一道面试题(多个线程按顺序输出)
- 多线程|java多线程实现奇偶数输出
- 面试题--三个线程循环打印ABC 10次(另类解决方法)
- 用信号量(互斥锁)实现两个线程交替打印