How many ways are for creating a new thread in Java?

后端 未结 7 2141
清歌不尽
清歌不尽 2020-12-29 10:14

Actually, what other ways are available apart from extending the Thread class and implementing the Runnable interface?

相关标签:
7条回答
  • 2020-12-29 10:44

    There are only Two ways for creating a Thread already you have mentioned but a third way is there to invoke the Thread.

    In java1.5 there is another way to invoke a thread. That is by “ExecutorService”. All these classes are from the “java.util.concurrent” package. There are various ways to create a “ExecutorService” using “Executors” factory class. The following is one of the way to create “ExecutorService”..

    ExecutorService es= Executors.newSingleThreadExecutor();

    RunnableImpl r = new RunnableImpl();

    Future fu=es.submit(r);

    Using “ExecutorService” methods we can submit eighter Runnable or Callable to the service for execution.

    How ever this cannot be said as the new way to create a Thread. It is because ExecutorService internally uses “ThreadFactory” class to create a new thread which internally uses eighter first or second method. So we have to say that there are only two ways to create threads but there is a new way in java1.5 to invoke a thread but not to create a Thread.

    0 讨论(0)
提交回复
热议问题