用java语言实现线程互斥执行和同步协调通信,参照黑马程序员网课:

 Java传统线程通信 随笔

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

package cn.qy.heima2;

public class TraditionalThreadCommunication {

public static void main(String[] args) {
// TODO Auto-generated method stub
final Business business=new Business();
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<=50;i++)
{
business.sub(i);
}
}
}).start();

for(int i=1;i<=50;i++)
{
business.main(i);
}
}
}
//高内聚:将有关联的方法(算法相同,访问数据相同),写在同一个类里面
//要用到共同数据(包括同步锁)的若干方法应该归在同一个类身上,体现了高内聚和程序健壮性
class Business
{
private boolean shouldsub=true;
public synchronized void sub(int i)
{
while(!shouldsub)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++)
{System.out.println("sub thread 序号:"+j+",循环:"+i);}
shouldsub=false;
this.notify();
}
public synchronized void main(int i)
{
while(shouldsub)
{try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
for(int j=1;j<=100;j++)
{System.out.println("main thread 序号:"+j+",循环:"+i);}
shouldsub=true;
this.notify();
}
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄