您好,欢迎访问一九零五行业门户网

如何在Java中实现线程间通信?

什么是线程通信、如何实现?
所谓线程通信就是线程间相互发送数据,线程通信通常通过共享一个数据的方式实现。
线程间会根据共享数据的情况决定自己该怎么做,以及通知其他线程怎么做。
线程通信常见模型
生产者与消费者模型:生产者线程负责生产数据,消费者线程负责消费数据。
要求:生产者线程生产完数据后,唤醒消费者,然后等待自己;消费者消费完该数据后,唤醒生产者,然后等待自己
public class 多线程_5线程通信 extends thread{ public static void main(string[] args) { //定义线程类,创建一个共享的账户对象 account3 a=new account3("abc",0); //创建两个取钱的线程对象 new drawthread3(a,"小明").start(); new drawthread3(a,"小红").start(); //创建三个存钱的线程对象 new savethread(a,"存钱罐1号").start(); new savethread(a,"存钱罐2号").start(); new savethread(a,"存钱罐3号").start(); }}//存钱的线程类class savethread extends thread{ //接收处理的账户对象 private account3 acc; public savethread(account3 acc,string name){ super(name); this.acc=acc; } public void run(){ try { while (true){ //存钱 acc.savemoney(100000); //休眠2秒 thread.sleep(2000); } } catch (exception e) { e.printstacktrace(); } }}//取钱的线程类class drawthread3 extends thread{ //接收处理的账户对象 private account3 acc; public drawthread3(account3 acc,string name){ super(name); this.acc=acc; } public void run(){ try { while (true){ //取钱 acc.drawmoney3(100000); //休眠2秒 thread.sleep(2000); } } catch (exception e) { e.printstacktrace(); } }}class account3{ private string cartid; private double money;//账户余额 public account3() { } public account3(string cartid, double money) { this.cartid = cartid; this.money = money; } public string getcartid() { return cartid; } public void setcartid(string cartid) { this.cartid = cartid; } public double getmoney() { return money; } public void setmoney(double money) { this.money = money; } public synchronized void savemoney(double money) { //先获取是谁来存钱,线程名即是人名 string name=thread.currentthread().getname(); //判断账户是否有钱 try { if(this.money==0){ //没钱,存钱 this.money+=money; system.out.println(name+"来存钱,存了:"+money+"存钱后余额为:"+this.money); //有钱了 //唤醒所有线程 this.notifyall(); //锁对象,让当前线程进入等待 this.wait(); }else { //有钱,不存钱 //唤醒所有线程 this.notifyall(); //锁对象,让当前线程进入等待 this.wait(); } } catch (exception e) { e.printstacktrace(); } } public synchronized void drawmoney3(double money) { //先获取是谁来取钱,线程名即是人名 string name=thread.currentthread().getname(); try { //判断账户是否够钱 if(this.money>=money){ //有钱,取钱 this.money-=money; system.out.println(name+"来取钱成功,取了:"+money+"余额是:"+this.money); //没钱了 //唤醒所有线程 this.notifyall(); //锁对象,让当前线程进入等待 this.wait(); }else{ //余额不足 //唤醒所有线程 this.notifyall(); //锁对象,让当前线程进入等待 this.wait(); } } catch (exception e) { e.printstacktrace(); } }}
以上就是如何在java中实现线程间通信?的详细内容。
其它类似信息

推荐信息