谈synchronzied和Thread通信
在线程开发中,常常会遇到资源共享与同步的问题,synchronized就是来解决这个问题的,可是当谈到Thread通信,它就不能全部胜任了,还需要notify、wait等来配合。
public class Demo {private String msg = "";private boolean isend = false;public String getMsg() {return msg;}public synchronized void setMsg(String msg) {isend = false;this.msg += msg;System.out.println(this.msg);if(this.msg.length()==4){notify();System.out.println(Thread.currentThread().getName()+ "...好了");isend = true;try {System.out.println(Thread.currentThread().getName()+ "...wait");wait();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+"...notify");}}public synchronized void checkMsg(){if(this.msg.length()==4 || isend){this.msg = "";System.out.println(Thread.currentThread().getName()+ "...收到");notify();try {System.out.println(Thread.currentThread().getName()+"...wait");wait();} catch (InterruptedException e) {e.printStackTrace();}}}}