【问题标题】:A Thread as an object Java线程作为对象 Java
【发布时间】:2016-03-07 02:39:36
【问题描述】:

我想要一个继承自Thread 的对象集合;每个对象都在自己的线程中运行。

我尝试了extends Thread 并调用了super(),认为这样可以确保创建一个新线程;但没有...只有main 是正在运行的线程:(

每个人都告诉我,“实现Runnable 将您想要的代码放入run() 并将其放入线程对象中”。 由于两个原因,我不能这样做:

  1. 我的集合元素不是 Thread 类型的,如果我变形,我将不得不更改它的所有依赖项。

  2. run() 不能包含整个类...对吗?

所以我首先想知道,如果我想做的事情是可能的,并且 其次,如果可以,该怎么做?

【问题讨论】:

  • 欢迎回来 Olivier10178。 run() 可以包含一个内部类。
  • 您能提供更多信息吗?当然,您可以扩展 Thread 吗?然后你需要调用 Thread.start() 来让它们运行。
  • 您通常应该避免扩展Thread。你想达到什么目的?为什么不能直接将Runnables 传递给Thread
  • 什么是对象类型?并且...您希望每个对象在单独的线程中调用它的方法。对吧?
  • 为什么不能选择ExecutorService?

标签: java multithreading collections concurrency runnable


【解决方案1】:

super() 仅调用父构造函数(在您的情况下为默认的 Thread 构造函数)。实际启动新线程的方法是start()。正如其他人所说,扩展Thread 是糟糕的设计。

是的,你可以创建一个实现Runnable的类

class MySpecialThread implements Runnable {
    public void run() {
        // Do something
    }
}

你可以像这样在一个新线程中启动它:

Thread t = new Thread(new MySpecialThread());
// Add it to a collection, track it etc.
t.start(); // starts the new thread

1- 您可以使用以下示例使用Runnables 的集合 Threads 的集合。

MySpecialThread m = new MySpecialThread();
List<Runnable> runnables = new ArrayList<Runnable>();
runnables.add(m);
List<Thread> threads = new ArrayList<Thread>();
threads.add(new Thread(m));

2- 一个方法不能包含一个类,但是上面的例子MySpecialThread 是一个行为类似于任何其他类的类。可以编写构造函数,添加方法和字段等。

【讨论】:

  • 所以我需要一个单独的列表来包含线程就是你所说的。我不能只列出 1 个对象与线程等效的列表吗?
  • 我只是说你可以选择。如果您想要Thread 对象的列表,则不需要Runnables 的列表。我只是表明任何一个选项都是可能的。
  • 如果我只有一个 Runnables 列表;那我该如何启动线程呢??
  • 新线程(new MyRunnable()).start(); // MyRunnable 是你的 Runnable 任务
  • 对,我不需要在任何时候引用它们,因为它们可以自己管理?另外,如果我在 run() 中什么都没有,它还能工作吗?
【解决方案2】:

我推荐使用ExecutorService

让我们有一个使用ExecutorService的示例代码

import java.util.*;
import java.util.concurrent.*;

public class ExecutorServiceDemo {

    public static void main(String args[]){
        ExecutorService executor = Executors.newFixedThreadPool(10);
        List<Future<Integer>> list = new ArrayList<Future<Integer>>();

        for(int i=0; i< 10; i++){
            CallableTask callable = new CallableTask(i+1);
            Future<Integer> future = executor.submit(callable);
            list.add(future);
        }
        for(Future<Integer> fut : list){
            try {
                System.out.println(fut.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
    }
}

class CallableTask implements Callable<Integer>{
    private int id = 0;
    public CallableTask(int id){
        this.id = id;
    }
    public Integer call(){
        // Add your business logic
        return Integer.valueOf(id);
    }
}

输出:

1
2
3
4
5
6
7
8
9
10

如果你想使用 Thread 而不是 ExecutorService,下面的代码应该适合你。

import java.util.*;

class MyRunnable implements Runnable{
    private int id = 0;
    public MyRunnable(int id){
        this.id = id;
    }
    public void run(){
        // Add your business logic
        System.out.println("ID:"+id);
    }
}
public class RunnableList{
    public static void main(String args[]){
        List<Thread> list = new ArrayList<Thread>();
        for ( int i=0; i<10; i++){
            Thread t = new Thread(new MyRunnable(i+1));
            list.add(t);
            t.start();  
        }
    }
}

【讨论】:

  • 为什么要有 RunnableList??
猜你喜欢
  • 2014-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 2012-11-03
相关资源
最近更新 更多