java多线程编程——线程同步之同步函数

如何找出线程安全问题:

1.明确那些代码块是多线程运行代码

2.明确共享数据

3.明确多线程运行代码中哪些语句是操作共享数据的

同步函数示例:

class Save{
    private int sum;
    public synchronized void add(int n){
        sum+=n;
        System.out.println("sum="+sum);
    }
}
class Cus implements Runnable{
    private Save b=new Save();
    public void run(){
        for(int x=0;x<3;x++){
            b.add(100);
        }
    }
}
class Bank{
    public static void main(String[] args){
        Cus c=new Cus();
        Thread th1=new Thread(c);
        Thread th2=new Thread(c);
        th1.start();
        th2.start();
    }
}

 

posted @ 2017-01-21 22:43  抡起菜刀砍小强  阅读(816)  评论(0编辑  收藏  举报