首页 > 代码库 > 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(); } }
打印出来的结果为
代码块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(); } }
看打印序列
说明同步块可以锁定任何对象
就是说同步方法是锁定当前对象,同步方法块是可以锁定任何对象
java线程同步方法,方法块区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。