How to give name to ExecutorFramework threads in java




Program to How to give name to ExecutorFramework threads in java >


import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

class MyRunnable implements Runnable {

    @Override
    public void run() {

          System.out.println(Thread.currentThread().getName() + " = run()");

          try {
                 Thread.sleep(1000);
          catch (InterruptedException e) {
                 e.printStackTrace();
          }

    }
}

//Define your own ThreadFactory by implementing java.util.concurrent.ThreadFactory
class MyThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
          return new Thread(r"Thread 1"); //Give custom name to thread
    }
}

public class GiveNameToExecutorFrameworkThreads {
    public static void main(String[] args) {
          Executors.newSingleThreadExecutor(new MyThreadFactory()).submit(new MyRunnable());
    }
}


//output

//Thread 1 = run()




Read : ThreadGroup in java.


RELATED LINKS>

Important Thread methods (salient features, usage with programs)>

Sleep() method in threads - 10 key features with programs

Wait() and notify() methods- Definition, 8 key features, solving consumer producer problem with & without these methods and consequences of not using wait() and notify() methods.

Daemon threads - 12 salient features of Daemon Thread

2 alternate ways to stop thread, as stop() method is deprecated

Join() method - 10 salient features of join

Thread isAlive() method

interrupt() method of thread in java

holdsLock(object) method to find whether current thread holds the lock on monitor of specified object.

Thread priorities - setPriority() and getPriority() methods

Using Suspend and resume method in threads


Methods for Adding ShutdownHook and handling uncaught runtime exception >

Threads addShutdownHook method in java

Handling uncaught runtime exception generated in run method using - setDefaultUncaughtExceptionHandler method



eEdit
Must read for you :