5.synchronized锁重入

 

  
  
  
  
  
package demo1;/** * synchronized锁重入 * Created by liudan on 2017/6/5. */public class MyThread5_synchronized1 { /** * 父子类同步必须 都 使用synchronized关键字 */ static class Main { public int count = 10; public synchronized void operationSub() { try { count--; System.err.println("Main print count = " + count); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Sub extends Main { public synchronized void operationSub() { while (count > 0) { try { count--; System.err.println("Sub print count = " + count); Thread.sleep(100); super.operationSub(); } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * 关键字 synchronized 拥有锁重入的功能, 也就是使用 synchronized 的时候,当一个线程获得一个对象的锁后,再次请求此对象 * 是是能够再次获得该对象的锁。 */ public static void main(String[] args) { Thread t = new Thread(new Runnable() { @Override public void run() { Sub s = new Sub(); s.operationSub(); } }); t.start(); }}
相关文章
相关标签/搜索