日期:2014-05-20  浏览次数:20881 次

线程的挂起和唤醒如何操作?谢谢
我想将当前线程挂起   是用wait()吗?可是为何总报错?
Exception   in   thread   "Thread-1 "   java.lang.IllegalMonitorStateException
at   java.lang.Object.wait(Native   Method)
at   java.lang.Object.wait(Object.java:485)
还有如何唤醒已经挂起的线程?
高手能给个详细的例子吗?
谢谢

------解决方案--------------------
class Producer implements Runnable //缓冲区内容生产者
{
Q q;
public Producer(Q q)
{
this.q = q;
}

public void run()
{
int i = 0;
while(true)
{
synchronized(q) //和消费者同步
{
if (q.full)
{
try {q.wait();}catch(Exception e){}
}
if (i == 0)
{
q.name = "zhangsan ";
q.sex = "male ";
}
else
{
q.name = "lisi ";
q.sex = "female ";
}
q.full = true;
q.notify();
}
i = (i+1) % 2;
}
}
}

class Consumer implements Runnable
{
Q q;
public Consumer(Q q)
{
this.q = q;
}
public void run()
{
while(true)
{
synchronized(q)
{
if (!q.full)
{
try {q.wait();}catch(Exception e){}
}
System.out.print(q.name);
System.out.println( " " + q.sex);
q.full = false;
q.notify(); //wait notify语句必须放在synchronized中
}
}
}
}

class Q
{
public String name = "unknown ";
public String sex = "unknown ";
public boolean full = false;
}

class Threadcommunation
{
public static void main(String [] args)
{
Q q = new Q();
new Thread(new Producer(q)).start(); //传的都是一个q,所以synchronized(q)
new Thread(new Consumer(q)).start();
}
}