标题: 设计4个线程,其中两个每次对j加1,另外两个j每次减1,这样设计是否正确呢 [打印本页] 作者: lucky_xingxing 时间: 2012-3-20 19:37 标题: 设计4个线程,其中两个每次对j加1,另外两个j每次减1,这样设计是否正确呢 public class ThreadTest
{
public static void main(String [] args){
int i = 100;
ThreadAdd add = new ThreadAdd(i);
ThreadCut cut = new ThreadCut(i);
Thread t1 = new Thread(add);
Thread t2 = new Thread(add);
Thread t3 = new Thread(cut);
Thread t4 = new Thread(cut);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class ThreadAdd implements Runnable
{
private int i;
public ThreadAdd(int i){
this.i = i;
}
Object obj = new Object();
public void run(){
for(int j = 0;j<50;j++){
synchronized(obj){
i++;
}
System.out.println(i);
}
}
}
class ThreadCut implements Runnable
{
private int i;
public ThreadCut(int i){
this.i = i;
}
Object obj = new Object();
public void run(){
for(int j = 0;j<50;j++){
synchronized(obj) {
i--;
}
System.out.println(i);
}
}
} 作者: 张锐 时间: 2012-3-20 20:01
LZ感觉你这个思路有点乱,我给你写了个你看看对不。