使用多线程交替打印1--n,a进程打印1,4,7,……(3n+1),b进程打印2,7,10,……(3n+2),c进程打印3,6,9,……(3n)
涉及到多线程的同步,阻塞,wait,notify
代码如下
Num.java
public class Num {
private int num = 0;
public Num(int num) {
this.num = num;
}
public synchronized void printOne() {
try {
while (num%3!=1) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + "------->"
+ (num++));
Thread.sleep(1000);
this.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void printTwo() {
try {
while (num%3!=2) {
this.wait();
}
System.out.println(Thread.currentThread().getName() + "------->"
+ (num++));
Thread.sleep(1000);
this.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
}
public s