zoukankan      html  css  js  c++  java
  • 线程之验证同步函数锁

     1 /**
     2  * 同步函数的使用的锁是this
     3  * 
     4  * 同步函数的同步代码块的区别
     5  * 同步函数的锁是固定的this
     6  * 
     7  * 同步代码块的锁是任意的对象
     8  * 建议使用同步代码块
     9  * @author 罗摩衔那
    10  *
    11  */
    12 class Tickets implements Runnable
    13 {
    14     private int num=100;
    15     Object obj=new Object();
    16     boolean flag=true;
    17     
    18     public  void run()
    19     {    
    20         System.out.println("this:"+this);
    21         if(flag)
    22         {//如果为真走局部代码块
    23         while(true)
    24         {
    25             synchronized (obj)
    26             {
    27                   if(num>0)
    28                     {
    29                         try {Thread.sleep(10);}catch(InterruptedException e) {}
    30                         System.out.println(Thread.currentThread().getName()+"...obj..."+num--);
    31                     }
    32             }
    33             }
    34         }
    35         else//如果为假走函数代码块
    36         {
    37             while(true)
    38                 this.show();
    39         }
    40     }
    41     public synchronized void show()
    42     {        
    43          if(num>0)
    44         {
    45             try {Thread.sleep(10);}catch(InterruptedException e) {}
    46             System.out.println(Thread.currentThread().getName()+"...function..."+num--);
    47         }        
    48     }
    49 }
    50 public class SynLockDemo 
    51 {
    52      public static void main(String[] args)
    53      {
    54         Tickets t=new Tickets();
    55         System.out.println(t);
    56         
    57         Thread t1=new Thread(t);
    58         Thread t2=new Thread(t);
    59         
    60         t1.start();
    61         //让线程一暂时丧失执行权,切换到false走函数代码块
    62         try {t1.sleep(10);}catch(InterruptedException e) {}
    63         t.flag=false;
    64         t2.start();
    65      }
    66 }

    温馨小提示:本实例中之所以要在线程一开启下加上睡眠方法,因为如果不加上睡眠方法则线程一在拥有线程执行权的时候会把flag切换成false,导致无论是线程一还是线程二都走函数同步代码块.

  • 相关阅读:
    SoapUI 使用笔记
    git 使用笔记(二)
    git 使用笔记(一)
    jquery 拓展
    hdu 1024 Max Sum Plus Plus (DP)
    hdu 2602 Bone Collector (01背包)
    hdu 1688 Sightseeing (最短路径)
    hdu 3191 How Many Paths Are There (次短路径数)
    hdu 2722 Here We Go(relians) Again (最短路径)
    hdu 1596 find the safest road (最短路径)
  • 原文地址:https://www.cnblogs.com/zjm1999/p/9885888.html
Copyright © 2011-2022 走看看