如何在java中使用线程时安全地增量

如何在java中使用线程时安全地增量,java,multithreading,thread-safety,critical-section,Java,Multithreading,Thread Safety,Critical Section,大家好,我想知道我是否能得到一些建议,我正在尝试编写一个程序,可以计算有多少线程正在等待处理一个函数,然后一旦达到某个数字,它就会释放所有线程。但我的问题是我不能正确地递增,因为我可以同时处理递增代码,因此根本不递增它 protected synchronized boolean isOpen() { //this code just calls mymethod intrested where the problem lies lock.interested(); whi

大家好,我想知道我是否能得到一些建议,我正在尝试编写一个程序,可以计算有多少线程正在等待处理一个函数,然后一旦达到某个数字,它就会释放所有线程。但我的问题是我不能正确地递增,因为我可以同时处理递增代码,因此根本不递增它

protected synchronized boolean isOpen()
{
    //this code just calls mymethod intrested where the problem lies

  lock.interested();
    while(!lock.isReady())
    {
    }
    return true;// this statement releases all my threads

 }



public synchronized void  interested()
{

    count++;// how do i make this increment correctly with threads
    System.out.println(count+"-"+ lanes+"-"+ThreadID.get());
    if(count==lanes)
    {

        count =0;
        ready =true;
    }

}
编写一个程序,可以计算有多少线程正在等待 处理一个函数,然后一旦达到某个数,它就会被处理 释放所有线程

一个好的解决办法是使用

从手册中:

CountDownLatch是用给定的计数初始化的。等待方法 块,直到由于调用 方法,然后释放所有等待的线程并 任何后续调用都将立即等待返回。这是一个 一次性现象——无法重置计数。如果你需要 重置计数的版本,考虑使用循环屏障。< /P>
您可以找到一个很好的代码示例

您的方法的问题是一次只有一个线程可以进入
synchronized
方法,因此,您将永远不会继续,因为除了第一个线程外,所有线程都在等待进入
synchronized
方法,而第一个线程正在执行繁忙的等待循环。您必须使用
wait
,这不仅解决了繁忙等待的CPU周期浪费问题,而且还将释放
同步的
代码的相关锁,以便下一个线程可以继续:

protected synchronized boolean isOpen()
{
    lock.interested();
    while(!lock.isReady())
    {
        wait(); // now the next thread can enter isOpen()
    }
    notify(); // releases the previous thread wait()ing in this method
    return true;
 }
但是,请注意,由于您的代码被分割到多个不同的对象上,因此这种方法非常不可靠。强烈建议将维护计数器的代码和实现等待计数器的代码放在一个对象中,以便在同一个锁下运行。您的代码结构必须确保
interest()
不能在
lock
实例上调用
isOpen
而没有注意到。从您发布的两段代码片段中,无法推断是否是这样

You should not use synchronised. Because only one thread will acquire monitor at a time.
您可以使用倒计时闩锁。在初始化CountDownLatch时只需定义线程数

private CountDownLatch countDownLatch = new CountDownLatch(no_of_threads);
protected  boolean isOpen()
{
    //this code just calls mymethod intrested where the problem lies

    countDownLatch.countDown();
    countDownLatch.await();
    return true;// this statement releases all my threads
 }


  All the threads are waiting in countDownLatch.await(). Once the required amount of thread comes(countDownLatch.countDown() is called) it will allow to proceed. 

允许您使用AtomicInteger吗?实际上,我试图避免使用预先编程的东西,换句话说,如果我像穴居人一样编写代码,我从一开始就完全理解它是如何工作的。如果你想自己实现它,可能会复制@jambuls(又称“重新发明轮子”)然后像上面Jeanne建议的那样使用AtomicInteger。好吧,我用一个原子整数替换了count变量,它似乎仍然不正确。我使用incrementAndGet()方法