【发布时间】:2020-10-20 16:53:06
【问题描述】:
我正在尝试创建一个可运行的数组来存储工作类,然后使用 Thread 数组开始工作。
public class SimpleThreads {
public static void main(String[] args) {
System.out.println("main starts.");
int num1 = 5;
int num2 = 7;
// create Workers
Runnable r1 = new Worker(num1, num2);
Runnable r2 = new Worker(num1 * 10, num2 * 10);
Runnable[] runs = new Worker(num1, num2);
// create Threads to run Workers
Thread[] threads = new Thread[args.length];
for (int i = 0; i < args.length; i++) {
threads[i] = new Thread(runs[i]);
}
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
// start threads
t1.start();
t2.start();
// Returns the adition to the main
System.out.println(((Worker) r1).doCalc());
System.out.println(((Worker) r2).doCalc());
int grandTotal = 0;
grandTotal = ((Worker) r1).doCalc() + ((Worker) r2).doCalc();
System.out.println("The Grand Total " + grandTotal);
System.out.println("main ends.");
}
}
/*
* the class that becomes a thread, can be named anything, must have
* "implements Runnable" which requires the public void run() method
*/
class Worker implements Runnable {
private int val1;
private int val2;
private long threadId;
// constructor
Worker(int val1, int val2) {
this.val1 = val1;
this.val2 = val2;
}
// required method
public void run() {
threadId = Thread.currentThread().getId();
doCalc();
}
// does the actual work
public int doCalc() {
return val1 + val2;
// System.out.printf("[%03d] %3d + %3d = %3d\n", threadId, val1, val2, result);
}
}
基本上,有人可以帮我弄清楚我在这里做错了什么吗?我收到此错误 Type mismatch: cannot convert from Worker to Runnable[]Java(16777233)
我的预期结果应该是
创建一个可运行的worker数组
然后在我的线程数组中使用该可运行工作线程数组并自动启动线程,而不是对每个线程一一硬编码。
【问题讨论】:
-
这个语句应该做什么?
Runnable[] runs = new Worker(num1, num2); -
cannot convert from Worker to Runnable[],注意[]。
标签: java arrays function runnable java-threads