当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码,保证了线程的安全。
举例,在函数fun()前加synchronized关键字:
public class ThreadDemo {
public static void main(String args[]) {
UserBean user = new UserBean("Jack", 100);
MyThread s1 = new MyThread("A", user, 20);
MyThread s2 = new MyThread("B", user, -15);
MyThread s3 = new MyThread("C", user, 30);
MyThread s4 = new MyThread("D", user, 45);
MyThread s5 = new MyThread("E", user,-70);
new Thread(s1).start();
new Thread(s2).start();
new Thread(s3).start();
new Thread(s4).start();
new Thread(s5).start();
}
}
class MyThread implements Runnable{
private String name;
private UserBean user;
private int y = 0;
MyThread(String name, UserBean user,int y){
this.name = name;
this.user = user;
this.y = y;
}
public void run(){
user.fun(y);
}
}
class UserBean {
private String userName;
private int crash;
UserBean(String userName, int crash){
this.userName = userName;
this.crash = crash;
}
public String getUserName(){
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public synchronized void fun(int x) {
try{
Thread.sleep(100);
this.crash += x;
System.out.println(Thread.currentThread().getName() +"_y is:" + x + ", and crash is: " + crash);
Thread.sleep(100);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果如下:
Thread-0 _y is:20, and crash is: 120
Thread-4 _y is:-70, and crash is: 50
Thread-3 _y is:45, and crash is: 95
Thread-2 _y is:30, and crash is: 125
Thread-1 _y is:-15, and crash is: 110
若去掉synchronized关键字:
Thread-1 _y is:-15, and crash is: 105
Thread-4 _y is:-70, and crash is: 110
Thread-2 _y is:30, and crash is: 180
Thread-0 _y is:20, and crash is: 120
Thread-3 _y is:45, and crash is: 150
上面的运行结果是混乱的,原因是多个线程并发访问了竞争资源user,并对user的属性做了改动。