将可运行对象转换为可运行的Worker数组

huangapple go评论83阅读模式
英文:

Converting Runnable into an array of runnable Workers

问题

我正在尝试创建一个可运行的数组,其中存储了工作类,然后使用线程数组来启动这些工作。

public class SimpleThreads {
  public static void main(String[] args) {
    System.out.println("main starts.");

    int num1 = 5;
    int num2 = 7;

    // 创建工作类实例
    Worker worker1 = new Worker(num1, num2);
    Worker worker2 = new Worker(num1 * 10, num2 * 10);

    // 创建可运行的数组以保存工作类实例
    Runnable[] runs = new Runnable[]{worker1, worker2};

    // 创建线程数组以运行可运行的实例
    Thread[] threads = new Thread[runs.length];

    for (int i = 0; i < runs.length; i++) {
      threads[i] = new Thread(runs[i]);
    }

    // 启动线程
    for (Thread thread : threads) {
      thread.start();
    }

    // 输出主线程返回的结果
    System.out.println(worker1.doCalc());
    System.out.println(worker2.doCalc());

    // 计算总和
    int grandTotal = worker1.doCalc() + worker2.doCalc();
    System.out.println("The Grand Total " + grandTotal);

    System.out.println("main ends.");
  }
}

class Worker implements Runnable {
  private int val1;
  private int val2;
  private long threadId;

  // 构造函数
  Worker(int val1, int val2) {
    this.val1 = val1;
    this.val2 = val2;
  }

  // 实现 Runnable 接口的方法
  public void run() {
    threadId = Thread.currentThread().getId();
    doCalc();
  }

  // 执行实际的工作
  public int doCalc() {
    return val1 + val2;
  }
}

请问有什么问题可以帮助解决吗?我遇到了一个错误:Type mismatch: cannot convert from Worker to Runnable[]Java(16777233)。我期望的结果是创建一个可运行的工作类数组,然后使用该数组与线程数组一起自动启动线程,而不是逐个硬编码每个线程。

英文:

I am trying to create a runnable array that stores worker classes then use a Thread array to start the works.

public class SimpleThreads {
public static void main(String[] args) {
System.out.println(&quot;main starts.&quot;);
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 &lt; 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(&quot;The Grand Total &quot; + grandTotal);
System.out.println(&quot;main ends.&quot;);
}
}
/*
* the class that becomes a thread, can be named anything, must have
* &quot;implements Runnable&quot; 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(&quot;[%03d] %3d + %3d = %3d\n&quot;, threadId, val1, val2, result);
}
}

Basically, can someone help me figure out what I am doing wrong here? I get this error Type mismatch: cannot convert from Worker to Runnable[]Java(16777233)

My Expected results should be

Creating an array of runnable workers

Then using that array of runnable workers with my thread array and starting threads automatically, instead of hardcoding each thread 1 by 1.

答案1

得分: 1

好的,以下是翻译好的部分:

似乎你对概念有点混淆。

你将所有的线程和可运行对象存储在数组中,但接着你继续创建非数组实例并使用它们。
你声明了可运行对象和线程,但接着你直接从主线程调用了计算方法。

让我们首先清理一下启动部分:

public class SimpleThreads {
  public static void main(String[] args) {
    System.out.println("main starts.");

    int num1 = 5;
    int num2 = 7;

    // 构建一个工作器(Worker)数组。
    Worker[] workers = new Worker[] {
      new Worker(num1, num2),
      new Worker(num1 * 10, num2 * 10)
    };

    // 创建用于运行工作器的线程并启动它们
    Thread[] threads = new Thread[workers.length];

    for (int i = 0; i < workers.length; i++) 
    {
      threads[i] = new Thread(workers[i]);
      threads[i].start();
    }

所以现在我们有了一个工作器Worker数组和一个线程数组
如果你愿意你可以将 `workers` 数组声明为 Runnable 类型但我们想要稍后使用工作器的方法

让我们看看是否可以从工作器中获取数据我们将添加一个 `getResult()` 方法

```java
class Worker implements Runnable {
  private int val1;
  private int val2;
  private int result;

  // 构造函数
  Worker(int val1, int val2) {
    this.val1 = val1;
    this.val2 = val2;
  }

  // 必需的方法
  public void run() {
      doCalc();
  }

  // 执行实际工作
  private void doCalc() {
     result = val1 + val2;
  }

  public int getResult() { return result; }
}

因此一旦我们的工作器完成我们可以调用 getResult() 来查看它的最终答案

所以回到主函数让我们等待线程完成然后将它们的结果相加

```java
int grandTotal = 0;

// 等待线程完成
for(int i=0;i<threads.length;i++)
{
    threads[i].join();
}

// 读取它们的结果
for (int i=0; i<workers.length;i++)
{ 
    grandTotal += workers[i].getResult();
}
System.out.println("The Grand Total " + grandTotal);
英文:

It seems you are a little mixed up in concepts.

You store all your threads and runnables in arrays, but then you go ahead and create non-array instances and use those.
You declare runnables and threads, but then you go ahead and call the calculation method straight from your main thread.

Let's clean up the startup part first:

public class SimpleThreads {
public static void main(String[] args) {
System.out.println(&quot;main starts.&quot;);
int num1 = 5;
int num2 = 7;
// Build an array of workers.
Worker[] workers = new Worker[] {
new Worker(num1, num2),
new Worker(num1 * 10, num2 * 10)
};
// create Threads to run Workers and start them
Thread[] threads = new Thread[workers.length];
for (int i = 0; i &lt; workers.length; i++) 
{
threads[i] = new Thread(workers[i]);
threads[i].start();
}

So, now we have an array of Workers and an array of Threads.
You could declare the workers array to be of type Runnable if you wish, but we want to use the worker's methods later.

Lets see if we can get data out of the workers. We'll add a getResult() method.

class Worker implements Runnable {
private int val1;
private int val2;
private int result;
// constructor
Worker(int val1, int val2) {
this.val1 = val1;
this.val2 = val2;
}
// required method
public void run() {
doCalc();
}
// does the actual work
private void doCalc() {
result = val1 + val2;
}
public int getResult() { return result; }
}

So, once our worker has completed, we can call getResult() to see what it's final answer is.

So, back to the main, let's wait for the threads to finish, and then add up their results.

int grandTotal = 0;
// Wait for threads to finish
for(int i=0;i&lt;threads.length;i++)
{
threads[i].join();
}
// Read their results
for (int i=0; i&lt;workers.length;i++)
{ 
grandTotal += workers[i].getResult();
}
System.out.println(&quot;The Grand Total &quot; + grandTotal);

huangapple
  • 本文由 发表于 2020年10月21日 00:53:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64449825.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定