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;
    }
}

 

posted @ 2015-06-11 13:59  Fredric_2013  阅读(225)  评论(0编辑  收藏  举报