idea安全
多線程模擬生成者消費者,需求生產者生產一條數據,消費者消費一條,交替執行多線程
建立數據載體(實體類)ide
public class UserInfo implements Serializable { private String username; private String usersex; }
建立生產者測試
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; } } }
建立消費者this
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()); } } } }
建立測試類idea
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(); }
結果spa
很顯然出現了線程安全問題線程
修改代碼3d
數據不亂了,可是還不是咱們想要的結果code
修改上述代碼
運行結果