class ThreadTest1{
private int j; public static void main(String args[]){
ThreadTest1 tt=new ThreadTest1();
Inc inc=tt.new Inc();
Dec dec=tt.new Dec();
for(int i=0;i<2;i++){
Thread t=new Thread(inc);
t.start();
t=new Thread(dec);
t.start();
}
} private synchronized void inc(){
j++;
System.out.println(Thread.currentThread().getName()+"-inc:"+j);
} private synchronized void dec(){
j--;
System.out.println(Thread.currentThread().getName()+"-dec:"+j);
} class Inc implements Runnable{
public void run(){
for(int i=0;i<100;i++){
inc();
}
}
} class Dec implements Runnable{
public void run(){
for(int i=0;i<100;i++){
dec();
}
}
}
}
设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1
本文展示了一个使用Java实现的简单线程同步示例。该示例通过一个名为ThreadTest1的类创建了两个匿名内部类Inc和Dec,分别实现了Runnable接口以递增和递减共享变量j。通过synchronized关键字确保了对j的操作是线程安全的。

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



