在博文多线程开发中提到使用synchronized实现同步有两种方法,一种是同步方法,另外一种是同步代码块。现在根据同样一个问题,分别给出同步方法和同步代码块的实现方法。
package test; public class ThreadDeadLock3 { public static void main(String args[]) { Info info = new Info(); // info作为参数传入两个线程当中 ProducerThread pt = new ProducerThread(info); ConsumerThread ct = new ConsumerThread(info); Thread producer = new Thread(pt, "producer"); Thread consumer = new Thread(ct, "consumer"); Thread consumer2 = new Thread(ct, "consumer2"); producer.start(); consumer.start(); //consumer2.start(); } // 资源类 static class Info { private String name; private String content; boolean flag=false; //getter and setter public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } // 获取name与content信息 public synchronized void get() { if(!flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+": "+this.getName() + ":-->" + this.getContent()); flag=false; this.notify(); } // 设置name与content信息 public synchronized void set(String name, String content) { if(flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.setName(name); this.setContent(content); //System.out.println(Thread.currentThread().getName()); flag=true; //this.notify(); this.notify(); } } // 生产者线程 static class ProducerThread implements Runnable { private Info info = null; // 构造函数,其参数是资源 public ProducerThread(Info info) { this.info = info; } @Override public void run() { for (int i = 0; i < 10; i++) { this.info.set("name" + i, "content" + i); } } } static class ConsumerThread implements Runnable { private Info info = null; // 构造函数,其参数是资源 public ConsumerThread(Info info) { this.info = info; } @Override public void run() { for (int i = 0; i < 10; i++) { this.info.get(); } } } }
上面这个程序的类图如下所示。通过这里类图我们来分析多线程的概念。
package test; public class ThreadDeadLock4 { public static void main(String args[]) { Info info = new Info(); // info作为参数传入两个线程当中 ProducerThread pt = new ProducerThread(info); ConsumerThread ct = new ConsumerThread(info); Thread producer = new Thread(pt, "producer"); Thread consumer = new Thread(ct, "consumer"); Thread consumer2 = new Thread(ct, "consumer2"); producer.start(); consumer.start(); // consumer2.start(); } // 资源类 static class Info { private String name; private String content; boolean flag = false; // getter and setter public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } // 获取name与content信息 public void get() { synchronized (this) { if (!flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ": " + this.getName() + ":-->" + this.getContent()); flag = false; this.notify(); } } // 设置name与content信息 public void set(String name, String content) { synchronized (this) { if (flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.setName(name); this.setContent(content); // System.out.println(Thread.currentThread().getName()); flag = true; // this.notify(); this.notify(); } } } // 生产者线程 static class ProducerThread implements Runnable { private Info info = null; // 构造函数,其参数是资源 public ProducerThread(Info info) { this.info = info; } @Override public void run() { for (int i = 0; i < 10; i++) { this.info.set("name" + i, "content" + i); } } } static class ConsumerThread implements Runnable { private Info info = null; // 构造函数,其参数是资源 public ConsumerThread(Info info) { this.info = info; } @Override public void run() { for (int i = 0; i < 10; i++) { this.info.get(); } } } }
通过对比我们可以看出,同步方法
public synchronized void set(String name, String content) { if(flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.setName(name); this.setContent(content); //System.out.println(Thread.currentThread().getName()); flag=true; //this.notify(); this.notify(); }
要转变为同步代码块只需要将synchronized关键字提到方法内部即可。
public void set(String name, String content) { synchronized (this) { if (flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.setName(name); this.setContent(content); // System.out.println(Thread.currentThread().getName()); flag = true; // this.notify(); this.notify(); } }
wait和notify方法是object的final方法,因此这个方法不能被重写。所以在程序中我们运行wait(),this.wait(),super.wait()都是一样的。都是执行超类Objcet的方法。
通常,多线程之间需要协调工作。例如,浏览器的一个显示图片的线程displayThread想要执行显示图片的任务,必须等待下载线程downloadThread将该图片下载完毕。如果图片还没有下载完,displayThread可以暂停,当downloadThread完成了任务后,再通知displayThread“图片准备完毕,可以显示了”,这时,displayThread继续执行。
以上逻辑简单的说就是:如果条件不满足,则等待。当条件满足时,等待该条件的线程将被唤醒。在Java中,这个机制的实现依赖于wait/notify。等待机制与锁机制是密切关联的。例如:
synchronized(obj) {
while(!condition) {
obj.wait();
}
obj.doSomething();
}
当线程A获得了obj锁后,发现条件condition不满足,无法继续下一处理,于是线程A就wait(),此时释放obj锁。在另一线程B中,如果B更改了某些条件,使得线程A的condition条件满足了,就可以唤醒线程A:
synchronized(obj) {
condition = true;
obj.notify();
}
具体例子如上述“同步代码块”中的代码,单独摘录如下:
// 获取name与content信息 public void get() { synchronized (this) { if (!flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ": " + this.getName() + ":-->" + this.getContent()); flag = false; this.notify(); } } // 设置name与content信息 public void set(String name, String content) { synchronized (this) { if (flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } this.setName(name); this.setContent(content); // System.out.println(Thread.currentThread().getName()); flag = true;//改变条件,则get方法中的if(!flag)条件不再满足,通过notify可执行if(!flag){}后面的代码 this.notify();//唤醒 } }
需要注意的概念是: