try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
this.sex = sex ;
}
public synchronized void get()
{
System.out.println(name+”--”+sex);
}
}
class Consumer implements Runnable
{
Q q=null;
public Consumer(Q q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println(q.name + "---->" + q.sex);
}
}
}
public class ThreadCommunation
{
public static void main(String [] args)
{
Q q=new Q();
new Thread(new Producer(q)).start();
new Thread(new Consumer(q)).start();
}
}
wati:告诉当前线程放弃监视器并进入睡眠状态,直到其他线程进入同一监视器并调用notify为止。
notify:唤醒同一对象监视器中调用wait的第一个线程。
notifyAll:唤醒同一对象监视器中调用wait的所有线程,具有最高优先级的线程首先被唤醒并执行。
class Q
{
private String name="陈琼";
private String sex="女";
boolean bFull = false ;
public synchronized void put(String name,String sex)
{
if(bFull)
wati() ; //后来的线程要等待
this.name = name ;
try
{
Thread.sleep(10);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
this.sex = sex ;
bFull = true ;
notify(); //唤醒最先到达的线程
}
public synchronized void get()
{
if(!bFull)
wait() ;
9
7
3
11
12
13
14
15
16
17
18
19
20
4
8
: