package thread;public class Test {
public static void main(String[] args) {
Queue q=new Queue();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}}
class Producer extends Thread{
Queue q;
public Producer(Queue q) {
this.q=q;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Producer put:"+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread{
Queue q;
Consumer(Queue q){
this.q=q;
}
@Override
public void run() {
while (true){
System.out.println("Consumer get:"+q.get());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Queue{
int value;
public void put(int i){
this.value=i;
}
public int get(){
return value;
}
}我都让Producer线程睡眠那么久了
搞不懂为什么Consumer线程的get 一直是0?顺便求前辈们说一下 wait 和notify的用法 调用的时候 必须要显示用this 或者引用变量 . 来调用么··我看孙鑫老师的视频 没有加 直接用的wait 和notifyjava 多线程 线程安全
public static void main(String[] args) {
Queue q=new Queue();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}}
class Producer extends Thread{
Queue q;
public Producer(Queue q) {
this.q=q;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Producer put:"+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer extends Thread{
Queue q;
Consumer(Queue q){
this.q=q;
}
@Override
public void run() {
while (true){
System.out.println("Consumer get:"+q.get());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Queue{
int value;
public void put(int i){
this.value=i;
}
public int get(){
return value;
}
}我都让Producer线程睡眠那么久了
搞不懂为什么Consumer线程的get 一直是0?顺便求前辈们说一下 wait 和notify的用法 调用的时候 必须要显示用this 或者引用变量 . 来调用么··我看孙鑫老师的视频 没有加 直接用的wait 和notifyjava 多线程 线程安全
解决方案 »
- 这段程序为什么编译不过去呢?
- 请问..有什么办法让父类去调用子类的方法
- 使用dom4j读取xml文档时,老是报以下错误!
- 高手请进!!谢谢!!
- 请教jdk1.5无法正常安装????
- [菜鸟学JAVA]刚开始学,装个JB7搞了一天,好好看了几页书,到了XML部分,要import javax.xml.parsers.*,org.w3c.dom.*,上网看了一下,好
- java的gui程序是怎么得到事件发生的消息的呢?
- 高手看看下面的代码哪里错了
- 求点拨一个MyEclipse的调试技术.
- ?????????????????
- 求助:函数调用问题--判断两个整数是否相等,在调用函数时不打印
- jdbc连接数据库问题
看你生产者的代码,哪里有给Queue的q添加值了呢?