java 多线程(synchronized)

package com.example;

public class App {

    public static void main(String[] args) {
        doRunable dr = new doRunable();
        Thread t1 = new Thread(dr,"Thread1");
        Thread t2 = new Thread(dr,"Thread2");
        
        t1.start();
        t2.start();
    }
}
package com.example;

public class doRunable implements Runnable {

    private Foo foo = new Foo();

    @Override
    public void run() {
        for (int i = 0; i < 4; i++) {
            this.foo.modify(10);
            
            
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            System.out.println(Thread.currentThread().getName() 
                    +"__"+ this.foo.getNum());
        }
    }
    
    public int getNum(){
        return this.foo.getNum();
    }
}
package com.example;

public class Foo {

    private int num = 100;

    public int getNum() {
        return this.num;
    }

    public int modify(int n) {
        /*Java语言中,每个对象都拥有一个访问代码关键部分并防止其他对象访问这段代码的monitor
            (每个对象都拥有一个对代码关键部分提供访问互斥功能的monitor)。这段关键部分是使用
         synchronized对方法或者代码标注实现的。同一时间在同一个monitor中,只允许一个线程
            运行代码的任意关键部分。*/
        synchronized (this) {
            System.out.println("in" + this.num + " " + n);
            int m = this.num;
            this.num = m - n;
            System.out.println("out" + this.num + " " + n);
        }
        
        return this.num;
    }
}

 

转载于:https://www.cnblogs.com/Fredric-2013/p/4568925.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值