码迷,mamicode.com
首页 > 编程语言 > 详细

java 多线程(synchronized)

时间:2015-06-11 14:32:48      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

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

 

java 多线程(synchronized)

标签:

原文地址:http://www.cnblogs.com/Fredric-2013/p/4568925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!