需求
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();
}
}