0

我正在尝试编写一个模拟多核 cpu 的程序。

我们有 3 个线程可以为我们完成核心工作。

还有一些任务将以 FIFO(先进先出)顺序完成。由于我是java中线程概念的新手,在对此进行了很多思考之后,我仍然对如何编写程序一无所知。

我只想知道如何以最简单的方式做到这一点以及必须使用哪些方法和类。

我正在考虑使用wait(),notifyAll()东西,但我不确定这是否可行。

在这个程序中,就像在每一步中,main 方法都会打印出来并增加主时钟,然后线程将根据主时钟的当前值决定是否必须打印一些东西(开始一个新任务,上下文切换) . 我会很感激任何提示。

输出必须如下所示:

Task 2 : 6 time units
Task 3 : 9 time units
Task 4 : 10 time units
Task 5 : 10 time units
Task 6 : 8 time units
Task 7 : 7 time units

--------------------

Master Clock : 0
  Core 2 started its first task of 7 time units
  Core 0 started its first task of 9 time units
  Core 1 started its first task of 6 time units
Master Clock : 1
Master Clock : 2
Master Clock : 3
Master Clock : 4
Master Clock : 5
Master Clock : 6
  Core 1 started context switch
Master Clock : 7
  Core 2 started context switch
Master Clock : 8
  Core 1 started a new task of 9 time units
Master Clock : 9
  Core 2 started a new task of 10 time units
  Core 0 started context switch
Master Clock : 10
Master Clock : 11
  Core 0 started a new task of 10 time units
Master Clock : 12
Master Clock : 13
Master Clock : 14
Master Clock : 15
Master Clock : 16
Master Clock : 17
  Core 1 started context switch
Master Clock : 18
Master Clock : 19
  Core 1 started a new task of 8 time units
  Core 2 started context switch
Master Clock : 20
Master Clock : 21
  Core 0 completed a total of 2 tasks
  Core 2 started a new task of 7 time units
Master Clock : 22
Master Clock : 23
Master Clock : 24
Master Clock : 25
Master Clock : 26
Master Clock : 27
  Core 1 completed a total of 3 tasks
Master Clock : 28
  Core 2 completed a total of 3 tasks
4

2 回答 2

2

根据您的描述,您似乎不需要(或不应该想要)Java 线程来进行此模拟。虚拟内核基于主时钟同步运行。您只需要一个代表主时钟的主循环,以及每个虚拟内核的操作队列。在每个主时钟步骤中,您确定每个虚拟内核的操作并执行它。不需要真正的线程。

于 2012-12-20T09:10:43.180 回答
0

您绝对应该了解更多关于 Java 并发的知识。这是一篇关于线程池和工作队列的文章,可以帮助您了解在 Java 中可以做什么 - http://www.ibm.com/developerworks/library/j-jtp0730/index.html

于 2012-12-19T19:38:41.350 回答