ExecutorService: ThreadGroup zuweisung?

osion

Bekanntes Mitglied
Hallo

Situation:

Ich habe:
Java:
public static ExecutorService threadPoolScanning = Executors.newFixedThreadPool(Processor.numberOfThread);
Java:
public static ThreadGroup groupPathScan=new ThreadGroup("pathScan")

und

Java:
ControlRunningProcess.threadPoolScanning.execute(new Thread(ControlRunningProcess.groupPathScan,new RekursionSearchScanning(this)));

Über excecute will ich ein neuer Thread starten, welche einer Threadgrupe zugewiesen wird.


Problem: Wenn ich den Thread ausserhalb vom ExecutorService erzeuge und starte, geht alles gut, aber innerhalb nimmt er immer die gruppe main.

java.lang.ThreadGroup[name=main,maxpri=10]
 
Doch hättest du aber auch gefunden, wenn du die API liest: HIER unter ThreadFactory

Auszug:

Creating new threadsNew threads are created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory() is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc.


Also so würde es gehen:

Java:
package test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class Test {
    
    public static ThreadGroup group;
    
    public static void main(String[] args) {
        group = new ThreadGroup("myGroup");
        ExecutorService es = Executors.newFixedThreadPool(8, new MyThreadFactory());
        Runnable r = () -> System.out.println(Thread.currentThread().getName() + ", " + Thread.currentThread().getThreadGroup().getName());
        es.execute(r);
        es.execute(r);
    }
    
    private static class MyThreadFactory implements ThreadFactory {

        private static final String THREAD_PREFIX = "THREAD-";
        private final AtomicInteger counter = new AtomicInteger(1);
        
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(group, r, THREAD_PREFIX + counter.getAndIncrement());
        }
    }
}
 
Zuletzt bearbeitet:

Neue Themen


Zurück
Oben