使用lock1:启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15

需求

1:启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20…以此类推, 直到打印到75. 程序的输出结果应该为:

线程1: 1
线程1: 2
线程1: 3
线程1: 4
线程1: 5

线程2: 6
线程2: 7
线程2: 8
线程2: 9
线程2: 10

线程3: 71
线程3: 72
线程3: 73
线程3: 74
线程3: 75

.java

功能类

package home;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class NumPrint {
public int num=1;
private int bs=1;

final Lock lock=new ReentrantLock();
final Condition c1=lock.newCondition();
final Condition c2=lock.newCondition();
final Condition c3=lock.newCondition();

public void printFive() {
	for (int i = 0; i < 5; i++) {
		System.out.println(Thread.currentThread().getName()+":"+num++);
	}
	System.out.println("                       ");
	try {
		Thread.sleep(500);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
public void fun(int i) {
	lock.lock();
	try {
		while (bs!=i) {
			if (i==1) {
				try {
					c1.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if (i==2) {
				try {
					c2.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else {
				try {
					c3.await();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		//功能
		if (num<=75) {
			printFive();
		}
		
		if (i==1) {
			bs=2;
			c2.signal();
		}else if (i==2) {
			bs=3;
			c3.signal();
		}else {
			bs=1;
			c1.signal();
		}
	} finally {
		// TODO: handle finally clause
		lock.unlock();
	}
}

}

测试类

package home.test;

import home.NumPrint;

public class Na75Test {

public static void main(String[] args) {
	// TODO Auto-generated method stub
	NumPrint numPrint=new NumPrint();
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (numPrint.num<=75) {
				numPrint.fun(1);
			}
		}
	},"线程1").start();
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (numPrint.num<=75) {
				numPrint.fun(2);
			}
		}
	},"线程2").start();
	new Thread(new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (numPrint.num<=75) {
				numPrint.fun(3);
			}
		}
	},"线程3").start();
	
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值