【发布时间】:2013-03-06 00:52:24
【问题描述】:
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
程序仅卡在此处(不会终止)。
有人请解释我在这里做错了什么?
【问题讨论】:
-
我可以说这不是理解生产者/消费者问题的最佳方式。
-
@AliAlamiri:好的。这个例子有什么问题。你能提出其他建议吗?