2012-12-19 42 views
0

我正在尝试编写一个模拟多核cpu的程序。在Java中使用线程并发模拟多核CPU

我们有3个线程可以为我们完成核心任务。

还有一些任务将作为FIFO(先进先出)顺序完成。 由于我是java中线程概念的新手,在对此进行了大量的思考后,我对如何编写程序仍然无能为力。

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

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

在这个程序中,就像在每个步骤中主要方法将打印出来并递增主时钟,然后线程将根据当前值决定是否必须打印某些内容(开始一个新任务,上下文切换)的主钟。 我会欣赏任何提示。

输出必须看起来像这样的事情:

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 
+1

此问题太泛泛。你应该花一些时间来学习如何使用线程并思考你的问题,并且看看这些是如何连接的。它的方式是,没有办法回答你的问题。 – vanza

+0

我同意@vanza,但只是给你一些关于从哪里开始的提示,我会从学习如何使用线程开始(非常有用的概念),然后看看如何利用[定时器](http:// docs。 oracle.com/javase/6/docs/api/javax/swing/Timer.html)以解决您的特定问题。祝你好运! – aymeric

回答

2

从您的描述中可以看出,您不需要(或者应该需要)此模拟的Java线程。虚拟内核基于主时钟以锁步方式运行。您所需要的只是一个代表主时钟的主循环,以及每个虚拟内核的操作队列。在每个主时钟步骤中,确定每个虚拟内核的操作并执行它。没有真正的线程需要。