zoukankan      html  css  js  c++  java
  • Java基础之synchronized的讲解


    博客出自:http://blog.csdn.net/liuxian13183,转载注明出处! All Rights Reserved ! 


    关于锁,需要在特殊时刻用到,今天就来小分析一把。

    public class ThreadTest extends Thread {  
        private int threadNo;  
        public ThreadTest(int threadNo) {  
            this.threadNo = threadNo;  
        }  
        public static void main(String[] args) throws Exception {  
            for (int i = 1; i < 10; i++) {  
               new ThreadTest(i).start();  
                Thread.sleep(1);  
            }  
         }  
       
        @Override  
         public synchronized void run() {  
            for (int i = 1; i < 10000; i++) {  
                System.out.println("No." + threadNo + ":" + i);  
            }  
         }  
     }  

    这个程序实际上是以ThreadTest对象做为锁,将run方法执行的,实际上是对每个线程都没有加锁,就像一个门有一把锁,但十个都有钥匙,所以线程执行非常乱。
    view plaincopy to clipboardprint?
    public class ThreadTest2 extends Thread {  
     private int threadNo; private String lock;  
     public ThreadTest2(int threadNo, String lock) {  
      this.threadNo = threadNo;  
         this.lock = lock;   }  
    public static void main(String[] args) throws Exception {  
       String lock = new String("lock");  
         for (int i = 1; i < 10; i++) {    
      new ThreadTest2(i, lock).start();  
          Thread.sleep(1);  
         }  
      }    
    public void run() {    
     synchronized (lock) {  
          for (int i = 1; i < 10000; i++) {  
           System.out.println("No." + threadNo + ":" + i);  
        }     
     }    
     }  
     }
    这个程序是对每个run方法,加一个特定的锁lock,但这个对象是所以线程共用的,就像十个人共用一个厕所的门,只能一个一个来。
    关于锁的用途在于,如果拍摄一张照片,只有保存成功才能进行传输;所用保存时,先锁住;保存完毕,锁自然解开,就可以传输查看了。

    尼玛呀,吐个槽,CSDN怎么搞的,我把代码贴上,总是给我居中显示,把所有格式都去掉都不行,不知道怎么搞的。

  • 相关阅读:
    ZOJ 3765 Lights (zju March I)伸展树Splay
    UVA 11922 伸展树Splay 第一题
    UVALive 4794 Sharing Chocolate DP
    ZOJ 3757 Alice and Bod 模拟
    UVALive 3983 捡垃圾的机器人 DP
    UVA 10891 SUM游戏 DP
    poj 1328 Radar Installatio【贪心】
    poj 3264 Balanced Lineup【RMQ-ST查询区间最大最小值之差 +模板应用】
    【转】RMQ-ST算法详解
    poj 3083 Children of the Candy Corn 【条件约束dfs搜索 + bfs搜索】【复习搜索题目一定要看这道题目】
  • 原文地址:https://www.cnblogs.com/fengju/p/6174515.html
Copyright © 2011-2022 走看看