- 案例
- demo
场景:
A 线程打印 5 次 A,B 线程打印 10 次 B,C 线程打印 15 次 C,按照 此顺序循环 10 轮
步骤说明:
- 创建资源类,定义属性和 *** 作方法
- 判断;干活;通知—通知:先修改标志位,再通知其他线程
- 创建多个线程, *** 作资源类的方法
package com.java.juc.lock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class ShareResource{ private int flag = 1; private Lock lock = new ReentrantLock(); private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); private Condition c3 = lock.newCondition(); public void print5(int loop) throws InterruptedException { //上锁 lock.lock(); try{ //第二步 判断 干活 通知 //number != 0,则等待;number = 0,+1; while( flag != 1 ){ c1.await(); } //干活 for(int i = 1;i <= 5; i++){ System.out.println("第" + loop + "轮:print5===" + Thread.currentThread().getName() + " :: " + i); } //先修改标志位 flag=2; //通知其他线程 c2.signal(); } finally { //解锁 lock.unlock(); } } public void print10(int loop) throws InterruptedException { //上锁 lock.lock(); try{ //第二步 判断 干活 通知 //number != 0,则等待;number = 0,+1; while( flag != 2 ){ c2.await(); } //干活 for(int i = 1;i <= 10; i++){ System.out.println("第" + loop + "轮:print10===" + Thread.currentThread().getName() + " :: " + i); } //先修改标志位 flag=3; //通知其他线程 c3.signal(); } finally { //解锁 lock.unlock(); } } public void print15(int loop) throws InterruptedException { //上锁 lock.lock(); try{ //第二步 判断 干活 通知 //number != 0,则等待;number = 0,+1; while( flag != 3 ){ c3.await(); } //干活 for(int i = 1;i <= 15; i++){ System.out.println("第" + loop + "轮:print15===" + Thread.currentThread().getName() + " :: " + i); } //先修改标志位 flag=1; //通知其他线程 c1.signal(); } finally { //解锁 lock.unlock(); } } } public class ThreadDemo3 { public static void main(String[] args) { ShareResource share = new ShareResource(); //创建线程 new Thread(()->{ for(int i = 1; i <= 10; i++){ try { share.print5(i); } catch (InterruptedException e) { e.printStackTrace(); } } },"AA").start(); new Thread(()->{ for(int i = 1; i <= 10; i++){ try { share.print10(i); } catch (InterruptedException e) { e.printStackTrace(); } } },"BB").start(); new Thread(()->{ for(int i = 1; i <= 10; i++){ try { share.print15(i); } catch (InterruptedException e) { e.printStackTrace(); } } },"CC").start(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)