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

来源:互联网 发布:中职网络的主题班会 编辑:程序博客网 时间:2024/06/06 16:53
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();
}
}
0 0
原创粉丝点击