java implement threads in three ways, stop () and suspend () method Why not recommended

1 thread implementation

java5 ago, following two:
There are two methods, namely the use new Thread()and newThread(runnable)form of the first direct call thread的runmethod, so we tend to use Threadsub-categories, namely new SubThread(). The second call to runnablethe runmethod. Thread class are inherited and implement Runnable

1.1 basis Thread class

newThread(){}.start(); This indicates that the call Threadsubclass object runmethod, newThread(){}showing an Threadexample of an object anonymous subclass, the subclass plus runcode is as follows:

new Thread(){
    public void run(){
    	//代码
    }
}.start();

1.2 The Runnable class

new Thread(newRunnable(){}).start(); This indicates that the call Threadsubject receiving the Runnableobject runmethod, newRunnable(){}showing an Runnableexample of an anonymous object subclass, runnablethe subclass plus runcode is as follows:

new Thread(newRunnable(){
                  public void run(){
						//代码
                  }     
          }

    ).start();

1.3 thread pool wording

From java5way to create multi-threaded start, as well as some of the thread pool:

ExecutorService pool= Executors.newFixedThreadPool(3)
for(inti=0;i<10;i++){
		 pool.execute(new Runable(){public voidrun(){}});
}
//或者另外一种写法
Executors.newCachedThreadPool().execute(newRunable(){public void run(){}});
//或者又有另一种写法
Executors.newSingleThreadExecutor().execute(newRunable(){public void run(){}});

2 stop and suspend methods

By synchronizedkeyword modified synchronization method
against the use stop(), because it is not safe. It will release all locks acquired by a thread, and if the object is in an inconsistent state, so other threads can check and modify them in that state. The result is difficult to check out the real problem.

suspend()Methods prone to deadlock. Call suspend()time, the target thread will stop, but they still hold locked in before obtained. At this point, any other thread can access a locked resources, unless "挂起"the thread resumes running. 对任何线程来说,如果它们想恢复目标线程,同时又试图使用任何一个锁定的资源It will result in a deadlock. It should not be used suspend(), but should put a sign in his class Thread, the thread should be pointed out that active or suspended. If the flag indicates that the thread should hang, they use wait () command it enters the wait state. If the flag indicates that the thread should be restored, then use a notify () to restart the thread.

Published 334 original articles · won praise 186 · views 310 000 +

Guess you like

Origin blog.csdn.net/u012060033/article/details/103873590