本文主要是介绍三个线程轮流打印1-100(两种实现方式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class RunnableDemo {//synchronized关键字实现public static class TestDemo implements Runnable{private static Object lock = new Object();private static int count =0 ;int no;public TestDemo(int no){this.no = no;}@Overridepublic void run() {while (true) {synchronized (lock) {if (count > 100) {break;}if (count % 3 == this.no) {System.out.println(this.no + "--->" + count);count++;} else {try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}lock.notifyAll();}}}}//ReentrantLock实现public static class TestDemo2 implements Runnable{private int no;private static ReentrantLock lock = new ReentrantLock();private static Condition condition = lock.newCondition();private static int count;public TestDemo2(int no){this.no = no;}@Overridepublic void run() {while (true){lock.lock();if (count>100){break;}else {if (count%3 == this.no){System.out.println(this.no+"-->"+count);count++;}else {try {condition.await();} catch (InterruptedException e) {e.printStackTrace();}}}condition.signalAll();lock.unlock();}}}public static void main(String[] args) throws InterruptedException{Thread t1 = new Thread(new TestDemo2(0));Thread t2 = new Thread(new TestDemo2(1));Thread t3 = new Thread(new TestDemo2(2));t1.start();t2.start();t3.start();t1.join();t2.join(); t3.join();}
}
这篇关于三个线程轮流打印1-100(两种实现方式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!