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(); } } }
时间: 2024-11-17 07:22:34