synchronized 关键字

当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码,保证了线程的安全。
举例,在函数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的属性做了改动。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值