gpt4 book ai didi

java - 来自 java.util.concurrent 的线程

转载 作者:行者123 更新时间:2023-11-30 02:42:09 26 4
gpt4 key购买 nike

我有使用线程的代码,但我不使用 java.util.concurrent 中的线程,所以我想更改我的代码,但我有一些问题。

Thread thread = new Thread() {
public void run() {
doSomething();
}
};

我想使用像这样的线程执行器,那么我该如何做到这一点?在 java.util.concurrent 中是否有类似的方法?我尝试过:

ExecutorService executorService = Executors.newCachedThreadPool();
Runnable runnable = new Runnable() {
public void run() {
//my code doing something
}
};

我还有:

List<Runnable> threadsList = new ArrayList<Runnable>();

我有方法:

boolean isAllowedCreateNewThread(Runnable taskToRun){
for(int i = 0; i < threadsList.size(); i++){
Runnable th = threadsList.get(i);
if(th.isAlive())doSomething(); //isAlive doesn't work since I have runnable instead of Thread
boolean isAllowed = true ;//I have here some bool function but it doesn't matter
if(isAllowed){
threadsList.add(taskToRun);
//service.submit(taskToRun);
executorService.execute(taskToRun);
}
return isAllowed;
}

如果我有 List<Thread> threadsList = new ArrayList<Thread>();并且不要使用 ExecutorService 并将所有 Runnable 更改为它工作的线程。所以我认为我也必须改变,但如何改变呢?什么是关键字insted Thread?Runnable?或者是其他东西?我还有:

for(int i = 0; i < threadsList.size(); i++){
Thread th = threadsList.get(i);
if(th.isAlive())doSomething(); myThreadName.start();

我必须改变isAlive()类似于 java.util.concurrent 中的内容和myThreadName.start();因此,通常我想使用 Thread 类更改此代码,以使用 java.util.concurrent 中的线程进行编码

最佳答案

您可以将您的代码替换为以下代码段。

  1. 创建一个 Runnable 类。

    class MyRunable implements Runnable{
    public void run() {
    doSomething();
    }
    private void doSomething() {
    System.out.println("Thread Executing is " + Thread.currentThread().getId());
    }
    }
  2. 创建具有所需线程数的执行程序服务。这将创建所需数量的线程池。

    int numberOfThreads  = 4;  // number of threads you want to create
    ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);
  3. 为池中存在的每个线程创建 Runnable 并将其分配给您的执行程序。

    for(int i=0;i<numberOfThreads;i++){
    Runnable myRunable = new MyRunable();
    service.submit(myRunable);
    }

    service.shutdown(); // this is a must as not given ,it halts the termination of the program

    示例输出

    Thread Executing is 9
    Thread Executing is 10
    Thread Executing is 8
    Thread Executing is 11

所以整个代码将如下所示:

class MyRunable implements Runnable {
public void run() {
doSomething();
}

private void doSomething() {
System.out.println("Thread Executing is " + Thread.currentThread().getId());
}

public static void main(String[] args) {
int numberOfThreads = 4; // number of threads you want to create
ExecutorService service = Executors.newFixedThreadPool(numberOfThreads);

for(int i=0;i<numberOfThreads;i++){
Runnable myRunable = new MyRunable();
service.submit(myRunable);
}

service.shutdown();

}

}

关于java - 来自 java.util.concurrent 的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41330857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com