线程2开始打印,打印6,7,8,9,10,线程3再开始打印11,12,13,14,15.接下来再有线程打印16,17,18,19,20
如此往复,直到打印完75,线程均结束(使用Java实现)
实现代码如下:
package thread;
/**
*
* @author Joe
* @category 三个线程循环递增打印,线程1从1开始打印,打印1,2,3,4,5,接下来再由
* 线程2开始打印,打印6,7,8,9,10,线程3再开始打印11,12,13,14,15.接下来再有线程打印16,17,18,19,20
* 如此往复,直到打印完75,线程均结束
*/
public class PrintThread {
public int iCount = 1;
public void normal_print() {
for(int i = 0;i < 5;i++) {
System.out.println(Thread.currentThread().getName()+":"+iCount);
iCount++;
}
}
public static void main(String[] args) {
PrintThread pt = new PrintThread();
MyThread1 thread1 = pt.new MyThread1();
MyThread2 thread2 = pt.new MyThread2();
MyThread3 thread3 = pt.new MyThread3();
thread1.start();
thread2.start();
thread3.start();
}
class MyThread1 extends Thread {
public void run() {
while(iCount < 75) {
int temp = iCount % 15;
if(temp <= 5 && temp >= 1)
print_i(temp);
}
}
public synchronized void print_i(int temp) {
if(!(temp <= 5 && temp >= 1)) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
normal_print();
notifyAll();
}
}
class MyThread2 extends Thread {
public void run() {
while(iCount < 75) {
int temp = iCount % 15;
if(temp <= 10 && temp >= 6)
print_i(temp);
}
}
public synchronized void print_i(int temp) {
if(!(temp <= 10 && temp >= 6)) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
normal_print();
notifyAll();
}
}
class MyThread3 extends Thread {
public void run() {
while(iCount < 75) {
int temp = iCount % 15;
if(temp <= 15 && temp >= 11 || temp == 0)
print_i(temp);
}
}
public synchronized void print_i(int temp) {
if(!(temp <= 15 && temp >= 11 || temp == 0)) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
normal_print();
notifyAll();
}
}
}
运行结果:
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0:5
Thread-1:6
Thread-1:7
Thread-1:8
Thread-1:9
Thread-1:10
Thread-2:11
Thread-2:12
Thread-2:13
Thread-2:14
Thread-2:15
Thread-0:16
Thread-0:17
Thread-0:18
Thread-0:19
Thread-0:20
Thread-1:21
Thread-1:22
Thread-1:23
Thread-1:24
Thread-1:25
Thread-2:26
Thread-2:27
Thread-2:28
Thread-2:29
Thread-2:30
Thread-0:31
Thread-0:32
Thread-0:33
Thread-0:34
Thread-0:35
Thread-1:36
Thread-1:37
Thread-1:38
Thread-1:39
Thread-1:40
Thread-2:41
Thread-2:42
Thread-2:43
Thread-2:44
Thread-2:45
Thread-0:46
Thread-0:47
Thread-0:48
Thread-0:49
Thread-0:50
Thread-1:51
Thread-1:52
Thread-1:53
Thread-1:54
Thread-1:55
Thread-2:56
Thread-2:57
Thread-2:58
Thread-2:59
Thread-2:60
Thread-0:61
Thread-0:62
Thread-0:63
Thread-0:64
Thread-0:65
Thread-1:66
Thread-1:67
Thread-1:68
Thread-1:69
Thread-1:70
Thread-2:71
Thread-2:72
Thread-2:73
Thread-2:74
Thread-2:75