Java多线程信号量

时间:2016-05-25 07:31:52

标签: java multithreading

计数器变量不能准确反映增量的次数 方法被调用。为什么不,以及如何解决? (您不必编写代码, 只需使用英语。)

原件:

import java.util.*;
import java.lang.*;
import java.io.*;


class Foopadoop
{
public static int counter = 0;
public static void main(String[] args) throws Exception {
    Runnable r = new Runnable() {
        public void run() {
            while(true){
                counter++;
            }
        }
    };
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
}
}

我的,我添加了一个信号量,但我不确定我做得对,还是我想使用锁。

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.concurrent.Semaphore;

class Foopadoop
{
public static int counter = 0;
Semaphore lock = new Semaphore(0);
public static void main(String[] args) throws Exception {
    Runnable r = new Runnable() {
        try{public void run() {
            while(true){
                counter++;
                lock.acquire();
            }
        }
       }finally{
         lock.release();
        }
    };
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r);
    t1.start();
    t2.start();
}
}

2 个答案:

答案 0 :(得分:4)

这不是您使用Semaphore的方式。

您在访问共享资源之前获取它,并在以下时间之后释放它:

while (true) {
  try {
    lock.acquire();
    counter++;
  } finally {
    lock.release();
  }
}

由于您acquire首先,您还需要至少1个许可,否则acquire没有任何内容:

static Semaphore lock = new Semaphore(1);

synchronized块比Semaphore更容易:

while (true) {
  synchronized (Foopadoop.class) {
    counter++;
  }
}

或AtomicInteger:

static AtomicInteger counter = new AtomicInteger();

// ...

while (true) {
  counter.getAndIncrement();
}

答案 1 :(得分:0)

你也可以在while循环中加入Thread.sleep(ms),让它暂停当前线程一段时间,然后开始执行其他线程。否则当前线程可能会以自私的方式运行(自私线程)。