黑马程序员-线程间的通信

------- android培训java培训、期待与您交流! ----------

等待唤醒机制:

wait()

notify()

notifyAll()

用在同步里,因为要对持有监视器(锁)的线程操作,所以要使用在同步中,因为只有同步才具有锁。

必须标示出所操作的线程,只有同一个锁上的被等待的线程,可以被同一个锁上的notify唤醒。不可以对不同锁中的线程进行唤醒。

等待唤醒必须是同一个锁。

synchronized(r)

{

try

{

              r.wait();          //必须标示出所操作的线程,wait()持有r这个锁的线程

}

catch(Exceptione)

{}

…………..

       r.notify();

}

 

Jdk1.5之后出现condition接口里边有方法await()signal()signalAll()相当于wait(),notify(),notifyAll();

Lock接口中的方法:lock()获取锁;(Condition)   newCondition()返回绑定到此lock实例的新condition实例;unlock()释放锁;

import java.util.concurrent.locks.*;

import java.util.concurrent.locks.*;

class Resource

{

    private Stringname;

    privateintcount=1;

    privatebooleanflag =false;

   

    private Locklock = new ReentrantLock();

    private Conditionpro_con = lock.newCondition();

    private Conditioncus_con = lock.newCondition();

   

    publicvoid set(String name)throws InterruptedException

    {

       lock.lock();

       try {

          while(flag)

          {

             pro_con.await();

          }

          this.name=name+"---"+count++;

          System.out.println(Thread.currentThread().getName()+"...生产"+this.name);

          flag = true;

          cus_con.signal();

      

       }

       finally

       {

          lock.unlock();

       }     

    }

    publicvoid out()throws InterruptedException

    {

       lock.lock();

       try {

          while(!flag)

          {

             cus_con.await();

          }

          System.out.println(Thread.currentThread().getName()+".......消费"+this.name);

          flag = false;

          pro_con.signal();

       }

       finally

       {

          lock.unlock();

       }

    }

}

class Producerimplements Runnable

{

    private Resourceres;

    Producer(Resource res)

    {

       this.res=res;

    }

    publicvoid run()

    {

        while(true)

       {

          try

          {

             res.set("商品");

          }

          catch(InterruptedException e)

          {}

       }

    }

}

class Customerimplements Runnable

{

    private Resourceres;

    Customer(Resource res)

    {

       this.res=res;

    }

    publicvoid run()

    {

       while(true)

       {

          try

           {

             res.out();

          }

          catch(InterruptedException e)

          {}

       }

    }

}

publicclass ThreadTongXin {

    publicstaticvoid main(String[] args) {

    Resource res = new Resource();

    new Thread(new Producer(res)).start();

    new Thread(new Producer(res)).start();

    new Thread(new Customer(res)).start();

    new Thread(new Customer(res)).start();

    }

}

 

线程停止:

只要控制循环,就可以run方法结束,也就结束了线程

 

特殊情况:

当线程出于冻结状态,就不会读取到标记,那么线程就不会结束。

当没有指定的方式让冻结的线程回复到运行状态时,这时需要对冻结进行清除。强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。

Thread类提供了该方法:interrupt()

 

public class StopThread {

                                      publicstatic void main(String[] args) {

                                          Testt = new Test();

                                          Threadt1 = new Thread(t);

                                          Threadt2 = new Thread(t);

                                          t1.start();

                                          t2.start();

                                          inta = 1;

                                          while(true)

                                          {

                                                 if(a++==50)

                                                 {

                                                        //t.setFlag();

                                                        t1.interrupt();//强制让线程苏醒,恢复到运行状态。

                                                        t2.interrupt();

                                                        break;

                                                 }

                                                 System.out.println("main....."+a);

                                          }    

                                      }

 

}

class Test implements Runnable

{

                                      privateboolean flag = true;

                                      publicsynchronized void run()

                                      {

                                          while(flag)

                                          {

                                                 try

                                                 {

                                                        wait();

                                                 }

                                                 catch(InterruptedExceptione)

                                                 {

                                                        System.out.println(Thread.currentThread().getName()+".....Exception");

                                                        flag= false;

                                                 }

                                                 System.out.println(Thread.currentThread().getName()+".....");

                                          }

                                      }

                                      publicvoid setFlag()

                                      {

                                          flag= false;

                                      }

}

 

守护线程:setDaemon(true);             在线程启动之前使用。

当正在运行的线程都是守护线程时,java虚拟机退出。

t1.setDaemon(true);

t1.start();

 

join方法:

A线程执行到了B线程的join方法时,A就会等待,等B线程都执行完了,A才会执行。

join可以用来临时加入线程执行。

 

优先级:

线程默认优先级都是5

设置优先级:setPriority();   

MAX_PRIORITY  最高优先级代表10

MIN_PRIORITY            最低优先级代表1

NORM_PRIORITY         默认优先级代表5

 

例:t1.setPriority(Thread.MAX_PRIORITY)

 

yield()方法:暂停当前正在执行的线程对象,并执行其他线程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值