• 多线程静态同步函数的锁是class 对象


    /*
    	通过验证发现 同步函数如果被静态修饰后,不再以this 为锁
    
    	静态进内存时,内存中没有本类对象,但是一定有该类的字节码文件对象
    	类名.class  该对象的类型是class
    
    
    	静态的同步方法,使用的锁是该方法所在类的字节码文件对象。类名.class
    */
    
    class Ticket implements	Runnable
    {
    	private static int tick = 100;
    
    	boolean flag = true;
    
    	public void run()
    	{
    		if(flag)
    		{
    				while(true)
    				{
    				//	synchronized(this)
    					synchronized(Ticket.class)
    					{
    						if(tick>0)
    						{
    							try{Thread.sleep(10);}catch(Exception e){}
    							System.out.println(Thread.currentThread().getName() +" ..code..."+ tick--);
    
    						}
    					}
    				}
    		}
    		else
    			while(true)
    				show();//this.show();
    	
    	}
    	public  static synchronized void show()//静态同步函数 该类对应的字节码文件对象为锁
    	{
    		if(tick>0)
    		{
    			try{Thread.sleep(10);}catch(Exception e){}
    			System.out.println(Thread.currentThread().getName() +" .....show..."+ tick--);
    		}		
    	}
    
    }
    
    
    class StaticLockDemo
    {
    	public static void main(String []args)
    	{
    		Ticket t = new Ticket();
    		Thread t1 = new Thread(t);
    		Thread t2 = new Thread(t);
    	
    		t1.start();//开启第一个线程  但不一定马上执行
    		
    		t.flag = false;//改变标志
    		try{Thread.sleep(40);}catch(Exception e){}//让主线程睡眠40毫秒  保证第一个线程先开始运行 且标志位改变
    
    		t2.start();	
    	}
    }

  • 相关阅读:
    为什么需要Docker?
    shiro原理
    java面对对象
    mysql面试题
    spring boot +thymeleaf+ mybatis
    mysql语句级sql
    spring boot+spring cloud面试笔记
    Docker-compose配置
    Docker compose命令的使用
    Dockerfile操作命令说明
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258521.html
Copyright © 2020-2023  润新知