如何在java / scala中增加线程分布?

时间:2016-02-10 16:54:48

标签: java multithreading scala

我复制在非线程安全代码中复制exception,以便它在findEntry0 while loop处于无限循环中,因此我创建了此代码:

val map = mutable.Map[Int, String]()
val rand = new Random()
def nextInt() = rand.nextInt(1000000)

for (i <- 1 to 1000) {
  new Thread(new Runnable {
    def run(): Unit = {
      while (true) {
        val key = nextInt()
        map.put(key, "some string")
        map.contains(key)
        println(s"thread ${System.currentTimeMillis()} ${Thread.currentThread().getName}")
      }
    }
  }).start()
}
Thread.sleep(120000)

打印:

thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080460 Thread-251
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219
thread 1455123080657 Thread-219

正如您所看到的那样,线程正在运行sequentially而不是时间戳并行,我做错了什么?如何让它们实际同时运行?

我做错了什么?我希望线程能够同时运行。

1 个答案:

答案 0 :(得分:2)

您的样本不太可靠。实际上它正在发生你所期望的。 线程在您的机器上并行执行。但实际上您的处理器/核心数量有限,因此当前上下文在您创建的每个X毫秒1000个线程之间切换。显然在上下文从一个线程切换到另一个能够写入的行之前。

我建议你 - 将并行线程的数量减少到一些可数量,并在无限循环内添加10ms睡眠。  这使您可以看到所有线程同时工作的多样性。

thread 1455123868703 Thread-3
thread 1455123868703 Thread-6
thread 1455123868703 Thread-9
thread 1455123868703 Thread-8
thread 1455123868703 Thread-2
thread 1455123868703 Thread-7
thread 1455123868721 Thread-9
thread 1455123868721 Thread-2
thread 1455123868721 Thread-4
thread 1455123868721 Thread-5
thread 1455123868721 Thread-6
thread 1455123868721 Thread-8
thread 1455123868721 Thread-3
thread 1455123868721 Thread-7
thread 1455123868721 Thread-0
thread 1455123868721 Thread-1