Article Directory
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的run
method, so we tend to use Thread
sub-categories, namely new SubThread()
. The second call to runnable
the run
method. Thread class are inherited and implement Runnable
1.1 basis Thread class
newThread(){}.start()
; This indicates that the call Thread
subclass object run
method, newThread(){}
showing an Thread
example of an object anonymous subclass, the subclass plus run
code is as follows:
new Thread(){
public void run(){
//代码
}
}.start();
1.2 The Runnable class
new Thread(newRunnable(){}).start()
; This indicates that the call Thread
subject receiving the Runnable
object run
method, newRunnable(){}
showing an Runnable
example of an anonymous object subclass, runnable
the subclass plus run
code is as follows:
new Thread(newRunnable(){
public void run(){
//代码
}
}
).start();
1.3 thread pool wording
From java5
way 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 synchronized
keyword 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.