同步代码块联系

本文详细介绍了使用并发编程实现输入与输出的多线程操作,通过创建Input和Output类并实现Runnable接口,展示了如何利用资源锁(Resouce)同步线程之间的数据交互。程序通过两个线程分别进行输入和输出操作,确保数据的一致性和有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Input类负责输入,Output类负责输出。每输入一次 就要输出一次。Resouce是锁对象。

public class Input implements Runnable{
private Resouce res;
Input(Resouce res){
this.res=res;
}
@Override
public void run() {
// TODO Auto-generated method stub
int x=0;//用来控制将名称性别设置
while(true){
synchronized(res){
if(res.flag){
try{
res.wait();
}catch(Exception e){}
}
if(x==0){
res.name="隔壁老王";
res.sex="男";
}else{
res.name="roes";
res.sex="male";
}
x=(x+1)%2;
res.flag=true;
res.notify();
}
}
}

}


class Output implements Runnable{
private Resouce res;
Output(Resouce res){
this.res=res;
}
@Override
public void run() {
while(true){
synchronized(res){
if(!res.flag){
try{
res.wait();
}catch(Exception e){
}
}
System.out.println(res.name+"-----"+res.sex);
res.flag=false;
res.notify();
}
}
}

}

public class Resouce {
String name ;
String sex;
boolean flag=false;//此标志为false表明输入完毕,为true表明输出完毕
}

class Main{
public static void main(String[] args){
Resouce res=new Resouce();
Input in=new Input(res);
Output out=new Output(res);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值