静态同步方法-同步锁为:类名.class

package com.homework;
public class MyRunnable3 implements Runnable{
public static int sum = 0;
public boolean flag = true;
public Object obj = new Object();
@Override
public void run() {
for(int i=0;i<3;i++){
setSum();
}
}
    public static  synchronized void setSum(){//静态同步方法。---同步锁为MyRunnable3.class
    sum+=100;
    try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out
.println(Thread.currentThread().getName() + "存了100元,现有" + sum+":同步方法");
    }
}
package com.homework; public class MyRunnable3 implements Runnable{ public static int sum = 0; public boolean flag = true; public Object obj = new Object(); @Override public void run() { for(int i=0;i<3;i++){ setSum(); } }     public static  synchronized void setSum(){//静态同步方法。---同步锁为MyRunnable3.class     sum+=100;     try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out .println(Thread.currentThread().getName() + "存了100元,现有" + sum+":同步方法");     } }
经验分享 程序员 微信小程序 职场和发展