Java synchronized、wait、notify實現線程(生成消費者模式)

調用線程對象的run方法不會產生一個新的線程,雖然可以達到相同的執行結果,但執行過程和執行效率不同



package com.thread.wsleep.example1;

public class Hint {

private int count;

public int getCount() {
return count;
}


public void setCount(int count) {
this.count = count;
}

public void product()
{
this.setCount(this.getCount() + 1);
}
public void consume()
{
this.setCount(this.getCount() - 1);
}

}

=====================================================


package com.thread.wsleep.example1;


public class Thread1 implements Runnable {


private Hint hint;
public Thread1(Hint hint)
{
this.hint = hint;
}
@Override
public void run() {
try
{
synchronized(hint)
{
while(true)
{
while(this.hint.getCount()<10)
{
this.hint.product();
System.out.println("thread1 count:" + this.hint.getCount());
}

this.hint.notify();
this.hint.wait();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}

public Hint getHint() {
return hint;
}
public void setHint(Hint hint) {
this.hint = hint;
}


}

=========================================================


package com.thread.wsleep.example1;


public class Thread2 implements Runnable {


private Hint hint;
public Thread2(Hint hint)
{
this.hint = hint;
}

@Override
public void run() {
try
{
synchronized(hint)
{
while(true)
{
while (this.hint.getCount() > 5)
{
this.hint.consume();
System.out.println("thread2 count: " + this.hint.getCount());
}
this.hint.notify();
this.hint.wait();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Hint getHint() {
return hint;
}
public void setHint(Hint hint) {
this.hint = hint;
}


}

=============================================================


package com.thread.wsleep.example1;


public class Main {


/**
* @param args
*/
public static void main(String[] args) {
Hint hint = new Hint();
new Thread(new Thread1(hint)).start();
try
{
Thread.sleep(5000);
}
catch (Exception e)
{
e.printStackTrace();
}
new Thread(new Thread2(hint)).start();
}


}


發佈了47 篇原創文章 · 獲贊 21 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章