public class Q55_3 {
public static void main(String[] args) {
Q55_3.test t=new Q55_3().new test();
t.a();
}
int j=0;
public synchronized int incre(){
System.out.println(j);
return j++;
}
public synchronized int desce(){
System.out.println(j);
return j--;
}
class test{
public void a(){
for(int i=0;i<2;i++){
new Thread(new Runnable(){
public void run(){incre();}
}).start();
new Thread(){
public void run(){desce();}
}.start();
}
}
}
}
public static void main(String[] args) {
Q55_3.test t=new Q55_3().new test();
t.a();
}
int j=0;
public synchronized int incre(){
System.out.println(j);
return j++;
}
public synchronized int desce(){
System.out.println(j);
return j--;
}
class test{
public void a(){
for(int i=0;i<2;i++){
new Thread(new Runnable(){
public void run(){incre();}
}).start();
new Thread(){
public void run(){desce();}
}.start();
}
}
}
}
本文提供了一个使用Java编写的示例程序,展示了如何利用synchronized关键字实现线程间的同步操作。该程序定义了一个名为Q55_3的公共类,其中包含两个同步方法:incre()用于增加一个共享变量j的值并打印当前值;desce()则用于减少这个共享变量的值并打印当前值。此外,还定义了一个内部类test,该类中有一个方法a(),在a()方法中创建了多个线程分别调用这两个同步方法。

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



