我有使用线程的代码,但我不使用java.util.concurrent中的线程,所以我想更改我的代码,但我有一些问题。
Thread thread = new Thread() {
public void run() {
doSomething();
}
};我想像这个线程一样使用executor,那么我该怎么做呢?在java.util.concurrent?I中尝试过类似的方法:
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?还是别的什么?我还有:
for(int i = 0; i < threadsList.size(); i++){
Thread th = threadsList.get(i);
if(th.isAlive())doSomething(); myThreadName.start();我必须在java.util.concurrent和myThreadName.start();中将isAlive()更改为类似的内容,因此通常我希望使用Thread类将此代码更改为使用java.util.concurrent中的线程编写代码
发布于 2016-12-26 20:32:09
你可以用下面的代码段替换你的代码。
类MyRunable实现Runnable{ public void run() { doSomething();} private void doSomething() { System.out.println("Thread executor is“+ Thread.currentThread().getId());}}
int numberOfThreads = 4;//您想要创建ExecutorService服务的线程数=为池中存在的每个线程创建可运行的,并将其分配给您的executor。
for(int i=0;i
样本输出
线程执行是9线程执行是10线程执行是8线程执行是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();
}
}发布于 2016-12-26 20:32:40
您可以使用_java.util.concurren_t中的执行器。
Executor是用来创建和管理线程的,所以你不必直接这么做。
在您的示例中,它将是:
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> doSomething());有许多类型的执行器,您必须根据调用的上下文来决定使用哪种。
例如,如果你只想拥有一个线程,你可以使用:
Executors.newSingleThreadExecutor();固定的线程数,即10:
Executors.newFixedThreadPool(10);或者根据需要创建新的线程:
Executors.newCachedThreadPool();有关Executor的更多信息,请阅读here。
希望能有所帮助。
https://stackoverflow.com/questions/41330857
复制相似问题