序列号添加不同步

时间:2018-05-25 12:27:11

标签: java multithreading thread-safety threadpool

我无法知道放在我能想象的所有位置"同步"但它仍然不安全,帮助,非常感谢!多线程争辩要添加一个序列号& #39; a'。应该可以同步线程Demo的run方法吗?无论如何,我把它添加到" public void run()"同步时,它仍然显示不安全的消息。

package stackoverflow;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NumberEx {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ExecutorService service=Executors.newCachedThreadPool();
        for(int i=0;i<10;i++) {
            service.execute(new ThreadDemo());
        }
        service.shutdown();

    }
}


package stackoverflow;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadDemo implements Runnable  {
    private static volatile int a = 0;
    private static volatile List<Integer> list=new ArrayList<Integer>();
    static PrintWriter writer;
    static {
        try {
            writer=new PrintWriter("./src/out.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void run()  {

         while (a< 1000) {
                //critical section
                a= increment(a);
                //end
         }
            writer.close();

    }

    private static synchronized int increment(int a)  {

        writer.print("<<<<============"+Thread.currentThread().getName()+"========================     ");

        a=a+1;
        Integer temp=new Integer(a);

       writer.print(" Thread["+Thread.currentThread().getName()+"]" + ":"+ a);
       writer.print("      ============="+Thread.currentThread().getName()+"=======================>>>>>    "); 
        if(list.contains(temp)) {
            System.out.println("repeat number"+temp);
            Iterator<Integer> iter=list.iterator();
            while(iter.hasNext()) {
                System.out.print(iter.next()+" ");
            }
            System.exit(0);
        }else {
            list.add(temp);
        }
       writer.println(" "+temp+"\n");

        return a;
    } 

}

2 个答案:

答案 0 :(得分:0)

我可能错了,但我认为你需要包围

//critical section
a= increment(a);
 //end

使用synchronized块并引入一个这样的锁定对象:

private static final Object LOCK = new Object();

@Override
public void run() {

    while (true) {
        synchronized (LOCK) {
            if(a<1000){
                //critical section
                a = increment(a);
                //end
            }else{
                break;
            }
        }
    }
}

您还需要检查同步块内部的条件,否则您将获得高于1000的数字。

编辑。以前的回答是不正确的。

答案 1 :(得分:0)

抱歉这个愚蠢的问题,我最近了解了对象监视器,最后通过同步对象来解析ti