public class Threadsychn {
public static void main(String[] args) {
// TODO 自动生成的方法存根
final Foo f=new Foo();
Thread t=new Thread(){
public void run(){
f.add();
}
};
t.start();
f.add(2);
}
}
class Foo{
int a=0;
public synchronized void add(int b){
System.out.println("call add(b)");
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
a+=b;
System.out.println("over call add(b)");
}
public synchronized void add(){
System.out.println("call add()");
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
a++;
System.out.println("over call add()");
}
}
本文探讨了Java并发编程中的线程同步机制,通过实例展示了如何使用synchronized关键字实现线程安全,以及如何避免常见的并发问题。

被折叠的 条评论
为什么被折叠?



