public class ShareEntity { private String name; // 线程通讯标识 private Boolean flag = false; public ShareEntity() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getFlag() { return flag; } public void setFlag(Boolean flag) { this.flag = flag; } }
public class CommunicationThread1 extends Thread{ private ShareEntity shareEntity; public CommunicationThread1(ShareEntity shareEntity) { this.shareEntity = shareEntity; } @Override public void run() { int num = 0; while (true) { synchronized (shareEntity) { if (shareEntity.getFlag()) { try { shareEntity.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (num % 2 == 0) shareEntity.setName("thread1-set-name-0"); else shareEntity.setName("thread1-set-name-1"); num++; shareEntity.setFlag(true); shareEntity.notify(); } } } }
public class CommunicationThread2 extends Thread{ private ShareEntity shareEntity; public CommunicationThread2(ShareEntity shareEntity) { this.shareEntity = shareEntity; } @Override public void run() { while (true) { synchronized (shareEntity) { if (!shareEntity.getFlag()) { try { shareEntity.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(shareEntity.getName()); shareEntity.setFlag(false); shareEntity.notify(); } } } }
@RequestMapping("test-communication") public void testCommunication() { ShareEntity shareEntity = new ShareEntity(); CommunicationThread1 thread1 = new CommunicationThread1(shareEntity); CommunicationThread2 thread2 = new CommunicationThread2(shareEntity); thread1.start(); thread2.start(); }
thread1-set-name-0
thread1-set-name-1
thread1-set-name-0
thread1-set-name-1
thread1-set-name-0
thread1-set-name-1
thread1-set-name-0