public class ThreadTest
{
//定义全局变量
private int j;
public static void main(String args[]){
ThreadTest tt = new
ThreadTest();
//调用非静态的方法
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();
}
}
class Inc implements Runnable
{
public void run(){
for(int
i=0; i<50; i++){
inc();
}
}
}
class Dec implements Runnable
{
public void run(){
for(int
i=0; i<50; i++){
dec();
}
}
}
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);
}
}
设计四个线程,其中两个线程每次对 j 加 1,另外两个每次对 j 减 1,程序如下。,布布扣,bubuko.com
设计四个线程,其中两个线程每次对 j 加 1,另外两个每次对 j 减 1,程序如下。
原文:http://www.cnblogs.com/zfg-technology/p/3572281.html