多线程之间的通信

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();

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容