多线程--同步函数使用的锁是this
2014-07-11 17:58
447 查看
同步函数用的是哪一个锁呢?
函数需要被对象调用。那么函数都有一个所属对象引用。就是this。
所以同步函数使用的锁是this。
通过程序进行验证
需求:使用两个线程来买票。一个线程在同步代码块中。一个线程在同步函数中。都在执行买票动作。
如果同步函数被静态修饰后,使用的锁是什么呢?
通过验证,发现不在是this。因为静态方法中也不可以定义this。
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class 该对象的类型是Class
静态的同步方法,使用的锁是该方法所在类的字节码文件对象。 类名.class
函数需要被对象调用。那么函数都有一个所属对象引用。就是this。
所以同步函数使用的锁是this。
通过程序进行验证
需求:使用两个线程来买票。一个线程在同步代码块中。一个线程在同步函数中。都在执行买票动作。
package com.tan; class Ticket implements Runnable { private int tick = 100; // Object obj = new Object(); boolean flag = true; public void run() { if(flag) { while(true) { synchronized(this) //两个锁的对象要一样,这样能保证安全,否则会出现Thread-0....code : 0 { if(tick>0) { try{Thread.sleep(10);}catch(Exception e){} System.out.println(Thread.currentThread().getName()+"....code : "+ tick--); } } } } else while(true) show(); } public synchronized void show()//this { if(tick>0) { try{Thread.sleep(10);}catch(Exception e){} System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--); } } } class ThisLockDemo { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); //让主线程停10毫秒 ,这个时候能运行的只有t1线程 try{Thread.sleep(10);}catch(Exception e){} t.flag = false; t2.start(); } }
如果同步函数被静态修饰后,使用的锁是什么呢?
通过验证,发现不在是this。因为静态方法中也不可以定义this。
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。
类名.class 该对象的类型是Class
静态的同步方法,使用的锁是该方法所在类的字节码文件对象。 类名.class
class Ticket implements Runnable { private static int tick = 100; //Object obj = new Object(); boolean flag = true; public void run() { if(flag) { while(true) { 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(); } public static synchronized void show() { if(tick>0) { try{Thread.sleep(10);}catch(Exception e){} System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--); } } } class StaticMethodDemo { public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); try{Thread.sleep(10);}catch(Exception e){} t.flag = false; t2.start(); } }
相关文章推荐
- boost库学习随记六:使用同步定时器、异步定时器、bind、成员函数回调处理、多线程的同步处理示例等
- 毕向东讲解(摘)—7.多线程安全问题(同步函数的锁this验证)
- 验证多线程中同步函数锁是this对象
- 多线程(多线程-同步函数的锁是this)
- 多线程-验证同步函数的锁是this
- boost库学习随记六:使用同步定时器、异步定时器、bind、成员函数回调处理、多线程的同步处理示例等
- 多线程之同步函数使用的是this锁
- 面向对象-多线程(同步函数的锁this与静态同步函数的锁class)
- 面向对象-多线程(同步函数的锁是this与静态同步函数的锁是class)
- 多线程---同步函数的锁是this(转载)
- java多线程-同步函数的锁是this
- 多线程(四)——多线程安全问题之同步函数(This Lock )
- 证实同步函数使用的是this锁
- 关于Javascript定义函数和this使用的两点注意的地方
- Delphi Dll中多线程无法使用Synchronize同步的解决方法(转)
- Javascript定义函数和this使用
- 多线程 不使用同步工具, 手动协调线程依次执行
- linux 多线程和同步机制的使用
- linux 多线程和同步机制的使用
- js原生态函数 中使用 jQuery中的 $(this) 无效