码迷,mamicode.com
首页 > 编程语言 > 详细

java线程同步方法,方法块区别

时间:2014-11-19 01:12:54      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:线程   java   同步方法   同步方法块   thread   

先说同步方法,它到底是锁定的当前对象,还是当前类

代码块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();  
    } 
}

打印出来的结果为

bubuko.com,布布扣

由此可见是当前对象,而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();  
    } 
}

看打印序列

bubuko.com,布布扣

说明同步块可以锁定任何对象


就是说同步方法是锁定当前对象,同步方法块是可以锁定任何对象



java线程同步方法,方法块区别

标签:线程   java   同步方法   同步方法块   thread   

原文地址:http://blog.csdn.net/yaoqinggg/article/details/41258987

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!