一个线程交替运行的考题

来源:互联网 发布:保税货物需要上传数据 编辑:程序博客网 时间:2024/06/09 13:44

传智播客视频中讲过这样一道题:

子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着回到主线程循环100次,如此循环50,写出程序。

这其实主要使用了Thread类的wait()和notify()方法,根据标志符使两个线程交替运行。实现如下:

public class ThreadCommunication {/** * @param args */public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 50; i++) {business.sub(i);}}}).start();for (int i = 0; i < 50; i++) {business.main(i);}}}class Business {private boolean isSub=true;public synchronized void sub(int arg) {while (!isSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for (int i = 0; i < 10; i++) {System.out.println("sub thread " + i + " in circle " + arg);}notify();isSub = false;}public synchronized void main(int arg) {while (isSub) {try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for (int i = 0; i < 100; i++) {System.out.println("main thread " + i + " in circle " + arg);}notify();isSub = true;}}

原创粉丝点击