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

看打印序列


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


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



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值