java多线程current thread not owner 错误

qingcaolin 2010-08-13 11:20:34
刚刚写了个多线程的程序,系统报current thread not owner错误,望各位大虾指点指点

import java.util.Queue;
public class MyExec extends Thread {
private final Queue<Runnable> workQueue ;
private final Object o ;
private Runnable r = null;

public MyExec(Queue<Runnable> queue,Object o) {
this.workQueue = queue;
this.o = o;
}
public void run() {
while (true) {
//从对列中拿取对象,开始执行run方法,队列为空就阻塞
if (workQueue.isEmpty()) {
try {
[color=#FF0000]o.wait();//这个地方报异常

} catch (InterruptedException e) {
e.printStackTrace();
}
}
r = workQueue.remove();
r.run();
}
}
}

客户端类:
import java.util.Queue;

public class Client implements Runnable {
private Queue<Runnable> execQueue = null;
private int i = 0;
private final Object o ;
public Client(Queue<Runnable> queue,Object o,int i)
{
this.execQueue = queue;
this.o =o;
this.i = i;
}
public void start()
{
execQueue.add(this);
o.notify();
}
public void run() {
System.out.println("线程"+i+"开始运行");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("------------线程"+i+"运行结束退出");
}
}


主线程类:
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class MainTest {

public static void main(String[] args) {
int execThreadNum = 10;
int clientThreadNum = 200;
final Object o = new Object();
MyExec[] exec = new MyExec[execThreadNum];
Client[] client = new Client[clientThreadNum];
Queue<Runnable> workQueue = new ConcurrentLinkedQueue<Runnable>();
for(int i= 0;i<exec.length;i++)
{
exec[i] = new MyExec(workQueue,o);
exec[i].start();
}
for(int i = 0;i<client.length;i++)
{
client[i] = new Client(workQueue,o,i);
client[i].start();
}
}
}
[/color]

...全文
2445 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhuyouyong 2010-08-16
  • 打赏
  • 举报
回复
顶[Quote=引用 2 楼 east271536394 的回复:]
线程同步的问题:

synchronized 方法或是synchronized 块,将要多线程的地方,加一把锁。这样只允许一个线程,进来,进行操作。。其它的线程一直等待上一个线程调度完。才能执行。
[/Quote]
pywepe 2010-08-16
  • 打赏
  • 举报
回复
颜色也太不利于浏览了吧
thegodofwar 2010-08-15
  • 打赏
  • 举报
回复
一般

Obj.wait();
Obj.notify;

的使用要和synchronized联系在一块
East271536394 2010-08-15
  • 打赏
  • 举报
回复
线程同步的问题:

synchronized 方法或是synchronized 块,将要多线程的地方,加一把锁。这样只允许一个线程,进来,进行操作。。其它的线程一直等待上一个线程调度完。才能执行。
dracularking 2010-08-13
  • 打赏
  • 举报
回复
要像这样获得对象锁之后才能使用,否则就是current thread is not the owner of the object's monitor

synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧