• 线程之验证同步函数锁


     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,导致无论是线程一还是线程二都走函数同步代码块.

  • 相关阅读:
    C#快速开发平台(C/S架构+Winform+DevExpress+FastReport)
    C# Winform C/S系统快速开发框架企业版V4.5已发布,欢迎下载试用
    CSS3 Animation
    CSS3 Transition
    CSS3 Transform
    jQuery 屏蔽鼠标快速经过
    JQ插件jquery.fn.extend与jquery.extend
    font-size单位换算
    js获取客户端操作系统
    js数组的操作
  • 原文地址:https://www.cnblogs.com/zjm1999/p/9885888.html
Copyright © 2020-2023  润新知