zoukankan      html  css  js  c++  java
  • java线程同步方法,方法块差别

    先说同步方法。它究竟是锁定的当前对象,还是当前类

    代码块1

    package com.ssss;
    
    public class Thread1 implements Runnable {  
    	//public static Object  o=new Object();
    
        public void run() {
        	pt();
        }
        
        public synchronized void pt(){
        	int a=0;
            //synchronized(o) {  
                 for (int i = 0; i < 5; i++) {
               	  a++;
               	  try {
    					Thread.sleep(1000);
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
                      System.out.println(Thread.currentThread().getName() + " synchronized loop " + i + "++++" + a);  
                 }  
            //}  
        }
        
        
        public static void main(String[] args) {  
             Thread1 t1 = new Thread1();  
             Thread1 t2 = new Thread1();  
    
             Thread ta = new Thread(t1, "A");  
             Thread tb = new Thread(t2, "B");  
             ta.start();  
             tb.start();  
        } 
    }

    打印出来的结果为


    由此可见是当前对象,而A和B是两个不同的对象。所以打印序列就是混乱的


    代码块2

    看同步块

    package com.ssss;
    
    public class Thread1 implements Runnable {  
    	public static Object  o=new Object();
    
        public void run() {
        	pt();
        }
        
        public void pt(){
        	int a=0;
            synchronized(o) {  
                 for (int i = 0; i < 5; i++) {
               	  a++;
               	  try {
    					Thread.sleep(1000);
    				} catch (InterruptedException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
                      System.out.println(Thread.currentThread().getName() + " synchronized loop " + i + "++++" + a);  
                 }  
            }  
        }
        
        
        public static void main(String[] args) {  
             Thread1 t1 = new Thread1();  
             Thread1 t2 = new Thread1();  
    
             Thread ta = new Thread(t1, "A");  
             Thread tb = new Thread(t2, "B");  
             ta.start();  
             tb.start();  
        } 
    }

    看打印序列


    说明同步块能够锁定不论什么对象


    就是说同步方法是锁定当前对象,同步方法块是能够锁定不论什么对象



  • 相关阅读:
    推荐系统算法总结(转)
    【算法题】求最大子数组之和
    jQuery中的filter和find函数
    获取文件夹大小
    微博140字,英文算半个字,中文算一个字,如何实现?
    Xcode 4 添加 Three20 的方法
    應用程式的設定檔info.plist
    iphone中结束电话后返回自己的应用
    解决问题:The icon file must be 57x57 pixels, in .png format (19014)
    开发中的一些小细节代码分享
  • 原文地址:https://www.cnblogs.com/llguanli/p/8734140.html
Copyright © 2011-2022 走看看