多线程(四)多线程之间的通讯

it2026-03-10  8

 

 一.环境

  idea

二.多线程之间如何通讯,什么是多线程之间的通讯

2.1举例

多线程模拟生成者消费者,需求生产者生产一条数据,消费者消费一条,交替执行

创建数据载体(实体类)

public class UserInfo implements Serializable { private String username; private String usersex; } View Code

 

创建生产者

public class InputThread implements Runnable { UserInfo userInfo=new UserInfo(); //用来做向数据载体中放数据 public InputThread(UserInfo userInfo){ this.userInfo=userInfo; } public void run() { int count=0; while (true){ if(count==0){ userInfo.setUsername("小明"); userInfo.setUsersex("男"); }else if (count==1){ userInfo.setUsername("小红"); userInfo.setUsersex("女"); } count=(count+1)%2; } } } View Code

 

创建消费者

public class OutputThread implements Runnable { UserInfo userInfo=new UserInfo(); public OutputThread( UserInfo userInfo){ this.userInfo=userInfo; } public void run() { while (true){ if(userInfo!=null){ System.out.println("userName:"+userInfo.getUsername()+",userSex:"+userInfo.getUsersex()); } } } } View Code

 

创建测试类

public static void main(String[] args) { UserInfo userInfo=new UserInfo(); OutputThread outputThread=new OutputThread(userInfo); InputThread inputThread=new InputThread(userInfo); Thread t1=new Thread(outputThread); Thread t2=new Thread(inputThread); t1.start(); t2.start(); } View Code

 

结果

 

很显然出现了线程安全问题

修改代码

 

 数据不乱了,但是还不是我们想要的结果

2.2wait、notify、notifyAll()方法

修改上述代码

 

 

 

 

 

 

 

 运行结果

 

 

 

转载于:https://www.cnblogs.com/wy0119/p/8999803.html

相关资源:Windows下基于socket多线程并发通信的实现
最新回复(0)