Java5 before, as in the following two kinds:
The first type:
New Thread () {}.start (); This means that the run method of the thread subclass object is called , and new Thread () {} represents an instance object of an anonymous subclass of thread, and the subclass plus the run The code after the method is as follows:
New Thread () { Public void run () { }.start ();
The second type:
New Thread (New Runnable () {}). Start (); This means that the run method of the Runnable object accepted by the Thread object is called , and new Runnable () {} represents a Runnable An instance object of an anonymous subclass of runnable, with the following code for the subclass of the run method:
New Thread (new Runnable () { publicvoid run () { } } ). Start ();
starting with Java5 , there are a number of thread pools that create Multithreading:
Executorservice pool = Executors.newfixedthreadpool (3) for(inti=0;i<10;i++) {Pool.execute (Newrunable () { Public voidrun () {}}); } executors.newcachedthreadpool (). Execute (Newrunable () { Public voidrun () {}}); Executors.newsinglethreadexecutor (). Execute (Newrunable ({ Public voidrun () {}});
There are two ways to implement it, usingNew Thread ()AndNew Thread (runnable)form, the first kind of direct call
ThreadOfRunmethod, so we tend to useThreadSubclass, which isNew Subthread ()。 The second kind of tune
UseRunnableOfRunMethod.
There are two ways to implement this, namely, inheritanceThreadClasses and implementationsRunnableInterface
UseSynchronizedKeyword Retouching synchronization method
Against the use ofStop (), because it is unsafe. It unlocks all locks acquired by the thread, and if the object is at
In an incoherent state, then other threads can examine and modify them in that state. The results are difficult to check out
The real problem lies. The suspend () method is prone to deadlocks. when calling suspend () , the target thread will stop
Down, but still hold the lock that was acquired before that. At this point, no other thread can access the locked
source, unless the thread that is " suspended " resumes running. For any thread to say if they want to restore the target threads, the same
When you try to use any of the locked resources, you create a deadlock. Therefore , suspend () should not be used, but should be
place a flag in your own thread class that indicates whether the thread should be active or suspended. If the sign indicates that the line thread executes
When it hangs, it waits with wait () to enter the waiting state. If the flag indicates that the thread should be restored, use a notify ()
Restart thread
Java face question there are several ways to implement a thread in Java? What keyword modifies the synchronization method? Why is the Stop () and suspend () methods not recommended?