문제

In java, what are the suggested ways to implement the two thread requirements

  1. I would like the name a thread
  2. I would like the parent (or main) thread know if there are any exceptions by this child thread.

For 2, I understand that having a future object would be a better approach. So to implement the above two requirements below is a code I came up with

class MyRunnable implements Runnable {
  ....
}


MyRunnable myRunnable = new MyRunnable ();
FutureTask futureTask = new FutureTask(myRunnable, null);
Thread myThread = new MyThread(futureTask, "processing-thread");
myThread.start();
try {
   futureTask.get();
} catch (Exception e) {
   throw new RuntimeException(e)
}

This seems to be a lot of code for simple stuff. Any better ways?

Note - Using executorService is not an option since I have threads which are not doing similar tasks. Also executorService accepts a thread name prefix instead of a thread name. I want to give each thread a unique name.

도움이 되었습니까?

해결책

Using executorService is not an option since I have threads which are not doing similar tasks.

I don't see how this would matter.

Also executorService accepts a thread name prefix instead of a thread name. I want to give each thread a unique name.

So give each thread a name with a ThreadFactory. I have a class which I call a NamedThreadFactory.

I suspect what you would like the thread to do is reflect what the task is doing.

You can do this

ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Runnable() {
    public void run() {
        Thread.currentThread().setName("Working on task A");
        try {
            System.out.println("Running: "+Thread.currentThread());
        } finally {
            Thread.currentThread().setName("parked worker thread");
        }
    }
});
es.shutdown();

prints

Running: Thread[Working on task A,5,main]

BTW There is no point starting a thread and immediately waiting for it to finish. You may as well use the current thread.

다른 팁

For the naming:

ThreadFactory myFactory = new ThreadFactory(){
  @Override public Thread newThread( Runnable r ) {
       return new Thread( r, getName() )
  }

  private int number = 0;

  private String getName(){
      return "MyThread_" + (number++);
  }

}

There are other ways, too. This is the I like best, personnally.

---EDIT---

To give the thread completely different names, I would go another way:

One possibility would be to set the name inside the Runnable: See Peter's answer with one addition: instead of the fixed String, you could initialize a member variable of your Runnable implementation before starting the Thread.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top