synchronized关键字
解决的问题:
保证同一时刻,只有一个线程访问某个方法或代码片段,即保证线程安全的。
作用范围:
【synchronized修饰实例方法】验证:
package hccool._synchronized3;
/**
* @author hgh
* @Package hccool._synchronized3
* @createDate 2020/04/28 14:45
*/
public class Task {
public synchronized void print() {
try {
System.out.println("开始进入无参print()方法...");
print("【无参print()方法,调用一个参数的print()方法】");
Thread.sleep(2000);
System.out.println("\n");
System.out.println("无参print()方法执行完成...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void print(String key) {
System.out.println("进入有一个参数的print()方法,参数key值为:" + key);
}
public void print(String key,String value){
System.out.println("进入两个参数的非同步print()方法,参数key值为:" +
key + "参数value值为:" + value);
}
}
package hccool._synchronized3;
/**
* @author hgh
* @Package hccool._synchronized3
* @createDate 2020/04/28 14:50