I have following classes :
package com.akshu.multithreading;
public class ThreadResource {
static int a;
static boolean Value =false;
public synchronized int getA() {
while(Value == false){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Value= false;
notify();
return a;
}
public synchronized void setA(int a) {
while(Value == true)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ThreadResource.a = a;
Value=true;
notify();
}
}
------------------
/**
*
*/
package com.akshu.multithreading;
/**
* @author akshu
*
*/
public class MyThreadA implements Runnable {
int a = 0;
ThreadResource tR= new ThreadResource();
@Override
public void run() {
for (int i = 0; i < 15; i++) {
tR.setA(++a);
System.out.println(" value of a :"+a);
}
}
}
------------
package com.akshu.multithreading;
public class MyThreadB implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
ThreadResource tR =new ThreadResource();
for (int i = 0; i < 15; i++) {
System.out.println("getA()"+tR.getA());
}
}
}
----
package com.akshu.multithreading;
public class ThreadExecutionPoint {
public static void main(String args[]) {
Thread th1 = new Thread(new MyThreadA());
Thread th2 = new Thread(new MyThreadB());
th1.start();
th2.start();
}
}
我想通過上面的代碼,瞭解生產者消費者問題。當我執行上面的代碼我得到僵局生產者消費者
value of a :1
getA()1
計劃只得到困在這裏(不被終止)。
有人請解釋我在這裏做什麼錯?
我可以說這是不是瞭解生產者/消費者問題的最佳途徑。 – 2013-03-17 17:59:21
@AliAlamiri:好的。這個例子有什麼問題,請給我建議一些其他的東西。 – noone 2013-03-17 18:01:12
這可能有助於http://java.dzone.com/articles/concurrency-pattern-producer – 2013-03-17 18:06:52