您的位置:首页 >> 编程开发 >> Java >> J2SE >> 正文
J2SE RSS
 

Java之多线程(1)

http://www.rdxx.com 05年07月24日 21:14 JR 我要投稿

关键词: 多线程 , Java , 线程

        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 :


 
 
标签: 多线程 , Java , 线程 打印本文
 
 
  相关资讯
RSS
 
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站