zoukankan      html  css  js  c++  java
  • java中线程存活和线程执行的问题!

     1 /*
     2 下面的程序会出现下面的情况,当Thread-0, Thread-1, Thread-2都被wait的时候,可能会同时苏醒
     3     Thread-0 put
     4     Thread-1 put
     5     Thread-2 put
     6     Thread-3 get//在此处,Thread-3拿到锁之后,将所有的等待的线程唤醒,才有了下面的输出
     7     Thread-2 put
     8     Thread-1 put
     9     Thread-0 put
    10 */
    11 
    12 
    13    虽然多个线程会同时苏醒,但是只有一个能获得cpu的执行权!
    14    总之,同步中执行的只能是一个,但是存活的不一定就是一个!
    15 
    16 
    17 class DuckD{
    18     public void put(){
    19         
    20         synchronized(DuckD.class){
    21           
    22               System.out.println(Thread.currentThread().getName()+" put");
    23               try{
    24                  DuckD.class.wait();//Thread-0, Thread-1, Thread-2可能会同时在这里苏醒!
    25               }catch(InterruptedException e){
    26                  
    27               }
    28               //........
    29         }
    30     }
    31     
    32     public void get(){
    33         
    34         synchronized(DuckD.class){
    35 
    36                 DuckD.class.notifyAll();
    37               System.out.println(Thread.currentThread().getName()+" get");
    38               try{
    39                  DuckD.class.wait();
    40               }catch(InterruptedException e){
    41                  
    42               }         
    43         }
    44     }
    45 }
    46 
    47 class ProduceD implements Runnable{
    48     DuckD dk;
    49     ProduceD(DuckD dk){
    50        this.dk=dk;
    51     }
    52     public void run(){
    53        while(true)
    54          dk.put();
    55     }    
    56 }
    57 
    58 class ConsumeD implements Runnable{
    59     DuckD dk;
    60     ConsumeD(DuckD dk){
    61        this.dk=dk;
    62     }
    63     public void run(){
    64         while(true)
    65           dk.get();
    66     }    
    67 }
    68 
    69 class Test{
    70    public static void main(String[] args){
    71        DuckD dk=new DuckD();
    72        Thread t1=new Thread(new ProduceD(dk));
    73        Thread t2=new Thread(new ProduceD(dk));
    74        Thread t3=new Thread(new ProduceD(dk));
    75        Thread t4=new Thread(new ConsumeD(dk));
    76        
    77        t1.start();
    78        t2.start();
    79        t3.start();
    80        t4.start();
    81    }
    82 }
  • 相关阅读:
    私有数据
    三大框架的对比
    angular的优化
    teamview centos 配置
    各种语言HMAC SHA256实现
    HttpClient使用cookie
    Mysql 安装
    iOS Safari 中点击事件失效的解决办法
    java验证码Captcha
    js 表单验证
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/3920873.html
Copyright © 2011-2022 走看看