/*
需求:开启2条线程, 轮流执行打印操作, 执行结果如下:
线程1: 1
线程1: 2
线程1: 3
线程2: 4
线程2: 5
线程2: 6
线程1: 7
线程1: 8
线程1: 9
线程2: 10
线程2: 11
线程2: 12
线程1: 13
线程1: 14
线程1: 15
线程2: 16
线程2: 17
线程2: 18
以上需求执行代码如下,结果如图:
*/
public class Work {
public static void main(String[] args){
final HomeWork h=new HomeWork();
new Thread(){
public void run(){
for(int i=0;i<3;i++)
h.haha();
}
}.start();
new Thread(){
public void run(){
for(int i=0;i<3;i++)
h.hah();
}
}.start();
}
}
class HomeWork {
private int x = 1;
private int flag = 1;
public synchronized void haha() {
if (flag == 2) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("线程1:" + x++);
System.out.println("线程1:" + x++);
System.out.println("线程1:" + x++);
System.out.println();
flag = 2;
notify();
}
public synchronized void hah() {
if (flag == 1) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("线程2:" + x++);
System.out.println("线程2:" + x++);
System.out.println("线程2:" + x++);
System.out.println();
flag=1;
notify();
}
}
/*
但怎样能开启3条或者更多线程执行呢?
如:
线程1: 1
线程1: 2
线程1: 3
线程2: 4
线程2: 5
线程2: 6
线程3: 7
线程3: 8
线程3: 9
线程1: 10
线程1: 11
线程1: 12
线程2: 13
线程2: 14
线程2: 15
线程3: 16
线程3: 17
线程3: 18
.
.
.
*/
|
|