多线程通讯之共享内存二(可重用锁)
Posted 纳木错星空
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程通讯之共享内存二(可重用锁)相关的知识,希望对你有一定的参考价值。
1.三个线程交替各打印15次,如此循环10次。
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class ReentrantLockAndThreadTask { //三个任务依次执行15次,共执行10轮 public static void main(String[] args) { // TODO Auto-generated method stub final Transaction tran = new Transaction(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (int i = 0 ; i < 15; i ++){ tran.sub2(i); } } }).start(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (int i = 0 ; i < 15; i ++){ tran.sub3(i); } } }).start(); for (int i = 0 ; i < 15; i ++){ tran.sub1(i); } } } class Transaction{ private int turn = 1; ReentrantLock tranLock = new ReentrantLock(true); Condition condition1 = tranLock.newCondition(); Condition condition2 = tranLock.newCondition(); Condition condition3 = tranLock.newCondition(); public void sub1(int j){ tranLock.lock(); try { while (turn != 1){ //如果不是第一个线程的轮次就等待 condition1.await(); System.out.println("111"); } for (int i = 0 ; i < 15; i ++){ System.out.println(Thread.currentThread().getName()+"正在执行第:"+j+"次序列号是:"+i);; } turn = 2; condition2.signal(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ tranLock.unlock(); } } public void sub2(int j){ boolean ishold = tranLock.isHeldByCurrentThread(); int num = tranLock.getHoldCount(); tranLock.lock(); int num1 = tranLock.getHoldCount(); boolean ishold1 = tranLock.isHeldByCurrentThread(); try { while (turn != 2){ //如果不是第一个线程的轮次就等待 condition2.await(); System.out.println("222"); } for (int i = 0 ; i < 15; i ++){ System.out.println(Thread.currentThread().getName()+"正在执行第:"+j+"次序列号是:"+i);; } turn = 3; condition3.signal(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ tranLock.unlock(); } } public void sub3(int j){ tranLock.lock(); try { while (turn != 3){ //如果不是第一个线程的轮次就等待 condition3.await(); System.out.println("333"); } for (int i = 0 ; i < 15; i ++){ System.out.println(Thread.currentThread().getName()+"正在执行第:"+j+"次序列号是:"+i);; } turn = 1; condition1.signal(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ tranLock.unlock(); } } }
以上是关于多线程通讯之共享内存二(可重用锁)的主要内容,如果未能解决你的问题,请参考以下文章
JUC并发编程 共享模式之工具 JUC CountdownLatch(倒计时锁) -- CountdownLatch应用(等待多个线程准备完毕( 可以覆盖上次的打印内)等待多个远程调用结束)(代码片段