在工作培训中,我正在编写一个Java(我的经验为0)程序,该程序应满足以下条件:
Write a program that replicates distributed computing application
Create central 'scheduler' object which contains a list of M random numbers
Create N processor threads that retrieve a number from the scheduler then loop that many times before requesting another number
If no numbers are available from the scheduler, wait to request another number.
If no more numbers are left, all the threads should end.
到目前为止,我创建了一个带有随机数数组的对象,但我真的不知道如何进行多线程处理。有人可以指导我完成它吗?这是我到目前为止所拥有的,以及指示伪代码的注释。
public class ThreadDemo extends Thread
{
//create new array of arbitrary size 5
static int SIZE = 5;
static int[] myIntArray = new int[SIZE];
public ThreadDemo()
{
start();
}
class RunnableThread implements Runnable {
Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}
public static void main(String[] args)
{
for(int i=0; i<SIZE; i++)
{
myIntArray[i] = (int)(Math.random() * 10);
}
ThreadDemo scheduler = new ThreadDemo();
//create M processor threads that retrieve number from scheduler
//for(int i=0; i<SIZE; i++)
//
//if no threads available
//make the scheduler thread wait() ??
//if empty
//stop() the scheduler thread ??
}
}
有人能引导我走向正确的方向吗?
谢谢!
最佳答案
作为第一个指针:不要在构造函数中启动线程,也不要使用 Runnable
对象来启动使用其自身的线程。对于阅读代码的人来说,这都是非常令人困惑的。
这是我对这个问题的看法(希望我没有得意忘形):
class Scheduler {
private int[] numbers;
private AtomicInteger current = new AtomicInteger();
public Scheduler(int count) {
Random rand = new Random();
numbers = new int[count];
for(int i = 0; i < count; i++) {
numbers[i] = rand.nextInt();
if(numbers[i] < 0) numbers[i] *= -1;
}
}
public int getNextNumber() {
int local = current.incrementAndGet();
if(local >= numbers.length) {
return -1;
}
return numbers[local];
}
}
首先,我们定义 Scheduler
类,该类保存随机(正)整数数组,并根据原子递增计数器从数组中按需返回一个数字。
class Task implements Runnable {
private Scheduler scheduler;
public Task(Scheduler scheduler) {
this.scheduler = scheduler;
}
public void run() {
while(true) {
int limit = scheduler.getNextNumber(); // get next number
if(limit == -1) return; // no more numbers
System.out.println(limit);
for(int i = 0; i < limit; i++) {
// spin
}
}
}
}
Task
类保存每个线程执行的代码。每个线程无限循环地向调度程序
请求数字,直到数组耗尽。
public class Test {
public static void main(String[] args) throws InterruptedException {
Scheduler s = new Scheduler(100);
ExecutorService exec = Executors.newFixedThreadPool(4);
for(int i = 0; i < 4; i++) {
exec.submit(new Task(s));
}
exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
在主类中,我们设置了一个线程池并执行 4 个线程来完成上述任务。
关于java - 如何添加Java多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11362547/