Java多线程信号量

标签 java multithreading

计数器变量并不能准确反射(reflect)增量的次数 方法被调用。为什么不,如何解决? (你不必写代码, 只用英语。)

原文:

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();
}
}

最佳答案

这不是您使用 Semaphore 的方式。

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

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

由于您首先获取,因此您还需要至少 1 个许可,否则没有什么可获取:

static Semaphore lock = new Semaphore(1);

synchronized block 比 Semaphore 更容易:

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

或一个 AtomicInteger:

static AtomicInteger counter = new AtomicInteger();

// ...

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

关于Java多线程信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37430544/

相关文章:

java - 如何处理wait()和notify()?

c++ - 每个线程一个类实例,C++11

java.lang.OutOfMemoryError : Java heap space while reading excel with Apache POI 错误

java - Android游戏java boolean 解决方案

java - 与 Hibernate 额外列查询的多对多关系

java - XSLT 调用嵌入了 XML 的 java

java - Retrofit2不发送POST数据

Java 线程异常终止并出现消息为 null 的异常。

ruby - 处理在 Ruby 线程中引发的异常

c#为什么要把对象放在lock语句中