一個關於執行緒的經典面試題,要求用三個執行緒,按順序列印1,2,3,4,5.... 71,72,73,74, 75. 執行緒1先列印1,2,3,4,5, * 然後是執行緒2列印6,7,8,9,10, 然後是
阿新 • • 發佈:2019-01-22
package thread;
/**
*
* 一個關於執行緒的經典面試題,要求用三個執行緒,按順序列印1,2,3,4,5.... 71,72,73,74, 75. 執行緒1先列印1,2,3,4,5,
* 然後是執行緒2列印6,7,8,9,10, 然後是執行緒3列印11,12,13,14,15. 接著再由執行緒1列印16,17,18,19,20....以此類推,
* 直到執行緒3列印到75。
*
*/
public class NumberPrintDemo {
public static void main(String[] args) {
final Business business = new Business();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
business.print(Thread.currentThread().getName());
}
}
}, i + "").start();
}
}
}
class Business {
private int number = 0;
private int state = 1;
public synchronized void print(String name) {
int num = Integer.parseInt(name) + 1;
while (state != num) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5; i++) {
number++;
System.out.println("執行緒"+num + ":" + number);
}
state = state % 3 + 1;
this.notifyAll();
}
}
/**
*
* 一個關於執行緒的經典面試題,要求用三個執行緒,按順序列印1,2,3,4,5.... 71,72,73,74, 75. 執行緒1先列印1,2,3,4,5,
* 然後是執行緒2列印6,7,8,9,10, 然後是執行緒3列印11,12,13,14,15. 接著再由執行緒1列印16,17,18,19,20....以此類推,
* 直到執行緒3列印到75。
*
*/
public class NumberPrintDemo {
public static void main(String[] args) {
final Business business = new Business();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
business.print(Thread.currentThread().getName());
}
}
}, i + "").start();
}
}
}
class Business {
private int number = 0;
private int state = 1;
public synchronized void print(String name) {
int num = Integer.parseInt(name) + 1;
while (state != num) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 5; i++) {
number++;
System.out.println("執行緒"+num + ":" + number);
}
state = state % 3 + 1;
this.notifyAll();
}
}