多线程之间的通信

2017-05-05  本文已影响0人  arryluo

public class T8 {

public static void main(String[] args) {

final DB db=new DB();

new Thread(new Runnable() {

@Override

public void run() {

// TODO Auto-generated method stub

for (int i = 0; i <50; i++) {

db.zi(i);

}

}

}).start();

for (int i = 0; i <50; i++) {

db.main(i);

}

}

}

class DB {

private boolean flg = true;

public synchronized void main(int i) {

// 如果是true的话,就让主函数等待

if (flg) {

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

// 主函数

for (int j = 0; j < 5; j++) {

System.out.println("main:" + i);

}

this.flg = true;

this.notify();

}

public synchronized void zi(int i) {

if (!flg) {

// 等于false的话,那么我就

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

for (int j = 0; j < 10; j++) {

System.out.println("子函数:" + j);

}

this.flg = false;

this.notify();

}

}

上一篇下一篇

猜你喜欢

热点阅读