--java Training, Android training, iOS training,. NET training, look forward to communicating with you! ——-
Threads in Java
The operation of a program needs to start an application process, a process can create multiple threads, help the application to complete the multi-tasking operation, implementation of concurrent operation. In the Java thread is encapsulated into Thread
a class, multi-threaded operation only need to inherit a Thread
class, to implement its own function, and then open the threads, or you can implement an Runnable
interface, and then pass it to the Thread
object, and then start it.
Thread is created on start inheritance
Thread
Create a class and inherit the class Thread
, then implement the method of the Thread
class, run
fill in the method with run
your own code, then create the custom class and call its start
methods to start the custom thread.
//Introduce threadImportJava.lang.Thread;/** * Create your own thread to implement the Run method (put on what you want to do) */Class MyThread extends Thread {/** * The Run method that covers the super-class thread */ Public void Run() { for(intI=0; i<Ten; i++) {System.out.println ("section"+ i +"Secondary cycle"); }}}class ThreadDemo1 { Public Static void Main(string[] args) {//Create a custom thread and start it NewMyThread (). Start (); }}/* Program output: No. 0 cycle 1th cycle 2nd cycle 3rd cycle 4th Cycle 5th cycle 6th time Cycle 7th Cycle 8th cycle 9th time Cycle */
Realize
Runnable
An object that has been implemented Runnable
can be executed by an Thread
object.
ImportJava.lang.Thread;Importjava.lang.Runnable;/** * Create a class that implements the Runnable interface. */Class Myrunnable implements Runnable {/** * Implement the runnable Run method * / Public void Run() { for(intI=0; i<5; i++) {System.out.println ("Runable: the first"+ i +"Secondary cycle"); }}}class ThreadDemo2 { Public Static void Main(string[] args) {//Create a thread and create an object that implements the Runnable //construct it, and then start this thread NewThread (NewMyrunnable ()). Start (); }}/ * Program output: runable: No. 0 cycle runable: 1th cycle runable: 2nd cycle runable: 3rd cycles runable: 4th cycles * /
synchronized
The use
Since it is multi-threaded, there will be multithreading problems, such as accessing the same resource at the same time, resulting in unexpected results, which we do not want to see. In Java can be very simple to solve this problem, using synchronized
the operation to lock, synchronized
you can lock the object, you can also lock the function. synchronized
the differences between unused and used are compared below synchronized
.
Not used
synchronized
The situation
ImportJava.lang.Thread;ImportJava.lang.runnable;class Myrunnable implements Runnable {Private Static intI=0; Public void Run() { for(; i<Ten; i++) {Try{Thread.Sleep (Ten); }Catch(Exception e) {} print (i); } }Private void Print(intk) {System.out.println (k); }}class Demo { Public Static void Main(string[] args) {Myrunnable R =NewMyrunnable ();NewThread (R). Start ();NewThread (R). Start (); }}
You can see that the results are incorrect because two threads may enter the thread at the same time, and then print out two identical values.
002345678910
Used a
synchronized
After the situation
ImportJava.lang.Thread;ImportJava.lang.runnable;class Myrunnable implements Runnable {Private Static intI=0; Public void Run() {synchronized( This) { for(; i<Ten; i++) {Try{Thread.Sleep (Ten); }Catch(Exception e) {} print (i); } } }Private void Print(intk) {System.out.println (k); }}class Demo { Public Static void Main(string[] args) {Myrunnable R =NewMyrunnable ();NewThread (R). Start ();NewThread (R). Start (); }}
When for
lock processing is done, no two threads will enter the loop at the same time, so the printed number will not be faulted.
0123456789
synchronized
Lock object will have a flag bit (0/1), the default is 0, when the thread executes to synchronized
the lock object if the object's flag bit is 0, then set it to 1, otherwise wait. This flag can be called a "lock flag". This allows for thread synchronization.
Although the synchronized
problem of multi-threaded security has been solved, but there are some drawbacks, it will reduce the execution efficiency of the program, so, synchronized
can not be arbitrarily placed, should try to put it in the location must be used. An example of a singleton pattern:
public class single { private single minstance; private single () {} public static single getinstance () {if (minstance = = null) {synchronized (single.class) {i F (minstance = = null ) {minstance = New single (); }}} return minstance; }}
Here synchronized
can be added to the getInstance()
front, but this will greatly reduce the efficiency of execution, but also can be removed from the outer layer if(mInstance == null)
, but this will also increase the unnecessary judgment, that if you mInstance
have been created after you do not need to lock. If so, the above is the best way to write. The most inner if
judgment is necessary to illustrate, it can be assumed that in such a case, two threads are executed to the back of the first if
, then, if there is no inner layer of if
judgment, it mInstance
will be created two times, so the inner layer if
is indispensable.
wait
And
notify
The use
wait
And notify
is the two methods in object objects that are used for control in multiple threads, such as when you want to use two threads to print out Odd
and out alternately Even
, the code is as follows:
ImportJava.lang.Thread;ImportJava.lang.runnable;class Temp { Public Static BooleanFlag =false;} Class Odd implements runnable{ Public void Run() { while(true) {if(Temp.flag) {Try{Wait (); }Catch(Exception e) {}} System.out.println ("Odd"); Temp.flag =! Temp.flag;Try{Notify (); }Catch(Exception e) {}}}}class even implements Runnable { Public void Run() { while(true) {if(! Temp.flag) {Try{Wait (); }Catch(Exception e) {}} System.out.println ("even"); Temp.flag =! Temp.flag;Try{Notify (); }Catch(Exception e) {}}}}class Demo { Public Static void Main(string[] args) {NewThread (NewODD ()). Start ();NewThread (NewEven ()). Start (); }}
There are, of course, methods that notify
are notifyAll
used to wake all threads.
Use of lock
After JDK1.5, that is, after Java5.0, a lot of new content has been added, such as some classes for threading control, the use of which is Lock
equivalent to synchronized
, Lock
lock()
and unlock()
respectively, used for locking and unlocking, the general usage is as follows:
Importjava.lang.Runnable;ImportJava.lang.Thread;ImportJava.util.concurrent.locks.*;class Locks implements Runnable {PrivateLock lock =NewReentrantlock ();Private intindex =0; Public void Run() { while(true) {Lock.lock (); System.out.print (Index +" ");Try{Thread.Sleep ( -); }Catch(Exception e) {} index + +; Lock.unlock (); }}}class Demo { Public Static void Main(string[] args) {Locks Locks =NewLocks ();NewThread (Locks). Start ();NewThread (Locks). Start ();NewThread (Locks). Start (); }}
This allows you to print out sequentially 0 1 2 3 4 ···
.
Through Lock
the objects, we can create condition objects, such as
Condition condition = lock.newCondition();
You can then use condition.await();
and condition.signal()
to pause and wake a thread, and of course condition.signalAll()
to wake all threads.
Dark Horse programmer-java multithreaded operation