zoukankan      html  css  js  c++  java
  • synchronized(this)

    当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
     
    1. public class Thread1 implements Runnable {   
    2.      public void run() {   
    3.           synchronized(this) {    // 同步代码块  
    4.                for (int i = 0; i < 5; i++) {   
    5.                     System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);   
    6.                }   
    7.           }   
    8.      }   
    9.      public static void main(String[] args) {   
    10.           Thread1 t1 = new Thread1();   
    11.           Thread ta = new Thread(t1, "A");   
    12.           Thread tb = new Thread(t1, "B");   
    13.           ta.start();   
    14.           tb.start();   
    15.      }  
    16. }  
     
    运行结果: 

         A synchronized loop 0 
         A synchronized loop 1 
         A synchronized loop 2 
         A synchronized loop 3 
         A synchronized loop 4 
         B synchronized loop 0 
         B synchronized loop 1 
         B synchronized loop 2 
         B synchronized loop 3 
         B synchronized loop 4

    事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run(),参考JDK源代码:
    1. public void run() {  
    2.   if (target != null) {  
    3.    target.run();  
    4.   }  
    5. }
     
    http://blog.csdn.net/sunboy_2050/article/details/7675050
    http://blog.csdn.net/aboy123/article/details/38307539
  • 相关阅读:
    继续学习AJAX
    最近在看AJAX
    selenium学习模拟键盘按键操作
    二十三。克隆
    二十五。继承
    十八。类的属性
    二十一。第四章综合例题
    二十四。继承
    十七。对JAVA中堆和栈的细致了解
    十六。方法调用以及传参
  • 原文地址:https://www.cnblogs.com/lnas01/p/4962370.html
Copyright © 2011-2022 走看看