本文主要是介绍Java 多线程交替打印 0-100,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、synchronized和Object
- 线程应当绑定标志以便进行识别。
- 使用object.wait()对抢到锁不满足要求的线程进行休眠,这样满足要求的线程一定能抢到锁,执行完操作后再唤醒其他线程。
- 保存的打印次数和锁都应当只有一份,这样才能确保线程之间变量的统一。
public class PrintThread {public int times;public Object o;public int getTimes() {return times;}public PrintThread(Object o) {this.o = o;}public void setTimes(int times) {this.times = times;}public Object getO() {return o;}public void setO(Object o) {this.o = o;}public void print(int index) {while (times < 101) {synchronized (o) {if (times % 3 == index) {System.out.println("线程" + Thread.currentThread().getName() + " 打印 " + times);times = times + 1;}else {try {o.wait();} catch (InterruptedException e) {e.printStackTrace();}}o.notifyAll();}}}public static void main(String[] args) {Object o = new Object();PrintThread printThread = new PrintThread(o);Thread thread0 = new Thread(() -> {printThread.print(0);}, "0");Thread thread1 = new Thread(() -> {printThread.print(1);}, "1");Thread thread2 = new Thread(() -> {printThread.print(2);}, "2");thread0.start();thread1.start();thread2.start();}
}
2、Lock和Condition
synchronized只有一个等待队列,无法实现按需唤醒。
Lock可以创建多个Condition,每个condition都是一个等待队列,实现按需唤醒。
public class PrintThreadCondition {public int times;public void print(int index, Lock lock,Condition currentCondition, Condition nextCondition) {while (times < 101) {lock.lock();if (times % 3 == index) {System.out.println("线程" + Thread.currentThread().getName() + " 打印 " + times);times = times + 1;}else {try {currentCondition.await();} catch (InterruptedException e) {e.printStackTrace();}}nextCondition.signal();lock.unlock();}}public static void main(String[] args) {Object o = new Object();ReentrantLock lock = new ReentrantLock();Condition condition0 = lock.newCondition();Condition condition1 = lock.newCondition();Condition condition2 = lock.newCondition();PrintThreadCondition printThread = new PrintThreadCondition();Thread thread0 = new Thread(() -> {printThread.print(0, lock, condition0, condition1);}, "0");Thread thread1 = new Thread(() -> {printThread.print(1, lock, condition1, condition2);}, "1");Thread thread2 = new Thread(() -> {printThread.print(2, lock, condition2, condition0);}, "2");thread0.start();thread1.start();thread2.start();}
}
这篇关于Java 多线程交替打印 0-100的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!