您的位置:首页 > 编程语言 > Java开发

java 线程通讯 主线程运行10次接着子线程运行5次,如此反复运行20次代码实现

2014-03-28 22:07 501 查看
package cn.lmj201402;

public class TraditionalThreadCommunication

{

public static void main(String[] args)

{

final Business business = new Business();

new Thread(new Runnable()

{

@Override

public void run()

{

for(int i = 0;i<20;i++)

{

business.main();

}

}

}).start();

for(int i = 0;i<20;i++)

{

business.sub();

}

}

}

class Business

{

boolean b = true;

public synchronized void main()

{

if(!b)

{

try

{

wait();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

}

for(int i = 0;i<10;i++)

{

System.out.println("Main "+i);

}

b = false;

notify();

}

public synchronized void sub()

{

if(b)

{

try

{

wait();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

}

for(int i = 0;i<5;i++)

{

System.out.println("Sub"+i);

}

b = true;

notify();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐