Author: qlampskyface
Contact your author: xiaozuidaizhi@sina.com
It has been a lot of time in contact with the multi-thread, but also a lot of things, but always feel that it is not so moving, when Debug, it will be more worried about what problems in synchronization, think of "Programmer" Written code "This sentence, I feel that it is not fake. I finally had one day, I think it is time to figure out this question, so I will find relevant content on the Internet, and I can't find this stage. It should be seen, it is not too simple, it is a strike, I don't know what the cloud. I finally almost figured out, there were many misunderstandings. I used to be very different from the truth. I think of my time spent. I really feel a bit more, so write it out, one is to prevent yours, I will forget it again, and the other is to give a point like I understand that I can refer to the stuff. Gossip less, transfer to the topic!
First create from the thread. There are two forms of the creation of threads:
One is inheriting from the Thread class .hetive class is a specific class, ie not an abstract class, which encapsulates the behavior of threads. To create a thread, the programmer must create a new class exported from the Thread class. The programmer completes useful work by overlying the run () function of Thread. The user does not call this function directly; but by calling the Start () function of Thread (), the function calls Run (). E.g:
Public class test () {public static void main (String args []) {test t1 = new test (); test t2 = new test (); t1.start (); t2.start () } Public void run () {// do thread's things}}
The other is to implement the runnable interface, this interface has only one function, Run (), this function must be implemented by a class that implements this interface. E.g:
public class Test implements Runnable {Thread thread1; Thread thread2; public Test () {thread1 = new Thread (this, "1"); thread2 = new Thread (this, "2");} public static void main (String args [ ]) {Test t = new test (); t.startthreads ();} public void run () {// do thread's things} public void startthreads () {thread1.start (); thread2.start ();}}
Two creation methods look great, but they can unclear, maybe you will make your program a mess. The difference between the two:
1. When you want to inherit a certain class, you can only use the latter way.
2. The first kind of inheritance from Thread, only created its own object, but on quantity, there is a few threads to create several self-objects; the second type only creates a self-object, but creates a few THREAD objects. The difference between the two methods is this, please consider: If you create several self-objects in the first kind and start (), you will find that the code block that is unreasonable if Synchronized does not work. Methods actually have several threads to go in, and the same variable can actually have several threads to change it. (For example, the following code) This is because in this program, although you play a few threads, you have created several objects, and each thread corresponds to each object, each thread change And the objects of the occupied object are different, so there is a phenomenon of several threads entering a method. In fact, it is not a method, but the same method of different objects. So, this time you have to lock, you can only declare the method or variable as static. After adding Static, you will find that the thread can control the method, and it is impossible to have two threads to enter the same way. It is because it is not that every object has a method, but all objects have a method, this method is a static method. If you use the thread with the second method, you will not have the above situation, because at this time, you only created a self-object, so the properties and methods of your own objects are common for threads.
Therefore, I suggest that it is best to use the thread using the latter method.
public class mainThread extends Thread {int i = 0; public static void main (String args []) {mainThread m1 = new mainThread (); mainThread m2 = new mainThread (); mainThread m3 = new mainThread (); mainThread m4 = new MAINTHREAD (); magethread m6 = new mainthread (); m1.start (); m2.start (); m3.start (); m4.start (); m5.Start (); m6.Start ();} public synchronized void T1 () {i = i; try {thread.sleep (500);} catch (exception e) {} // Each thread enters the respective T1 () method Print each I system.out.println (thread.currentthread (). GetName () " i);} public void run () {Synchronized (this) {while (TRUE) {T1 ();} }}}
Let's talk about the four uses of Synchronized:
1. When the method declares, after the range operator (public, etc.), return to the type declaration (Void et al.). You can only have a thread to enter the method, and other threads want to call this method at this time. Can queue waiting, the current thread (that is, the other threads can enter after the method is executed. For example:
Public synchronized void synmethod () {// method} 2. Use a code block, Synchronized followed by parentheses, parentheses are variables, which once only one thread enters the code block. For example::
Public int synmethod (int A1) {Synchronized (A1) {// One thread can only be entered}} 3. Synchronized is an object, at this time, the thread is an object lock. For example:
Public class mythread implements runnable {public static void main (string args []) {mythread mt = new mythread (); thread t1 = new thread (MT, "T1"); thread t2 = new thread (MT, "T2") Thread T3 = New Thread (MT, "T3"); Thread T4 = New Thread (MT, "T4"); Thread T5 = New Thread (MT, "T5"); Thread T6 = New Thread (MT, "T6 "); T1.Start (); t2.start (); t3.start (); t4.start (); t5.start (); t6.start ();
Public void Run () {synchronized (this) {system.out.println (thread.currentthread (). getname ());}}}
For 3, if the thread is entered, the object lock is obtained, then other threads cannot be performed any operation on all objects of the class. The object-level use lock is usually a relatively rough method. Why do you want to lock the entire object without allowing other threads to use other synchronization methods in the object to access shared resources? If an object has multiple resources, it is not necessary to lock all threads outside only to let a thread use some of the resources. Since each object is locked, you can use the virtual object to be locked as follows:
Class FinegrainLock {
Mymemberclass X, Y; Object Xlock = New Object (), YLOCK = New Object ();
Public void foo () {synchronized (xlock) {// access x here}
// Do Something Here - But don't use shared resources
Synchronized (YLOCK) {// Access Y Here}}
Public void bar () {synchronized (this) {// Access Both x and y here} // do sometying here - but don't use shared resources}}
4. Synchronized is a class in brackets. For example:
Class arraywithlockorder {private static long Num_locks = 0; private long lock_order; private int [] arr;
Public arraywithlockorder (int [] a) {arr = a; synchronized (arraywithlockorder.class) {// -------------------------------------------------------------------------------------------------------------------------------------------- ------------- Here Num_locks ; // Lock number plus 1. Lock_order = num_locks; / / Set the unique Lock_Order for this object instance. }} Public long lockOrder () {return lock_order;} public int [] array () {return arr;}} class SomeClass implements Runnable {public int sumArrays (ArrayWithLockOrder a1, ArrayWithLockOrder a2) {int value = 0; ArrayWithLockOrder first = a1 // Reserved an arraywithlockorder last = A2; / / local copy of the array reference. INT size = a1.Array (). Length; if (size == a2.Array (). Length) {if (a1.lockorder ()> A2.lockorder ()) / / Determine and set the lock {//// order. First = a2; LAST = a1;} synchronized (first) {// locked the object in the correct order. Synchronized (last) {int [] arr1 = a1.Array (); int [] arr2 = a2.Array (); for (int i = 0; i
Value = arr1 [i] arr2 [i];}}} return value;} public void run () {// ...}}
For 4, if the thread enters, the thread is not performed in this class, including static variables and static methods, in fact, for synchronization of code blocks containing static methods and static variables, we usually use 4 to lock.
The relationship between the above four types:
The lock is associated with the object, each object has a lock, in order to execute the SYNCHRONIZED statement, the thread must be able to get the lock specified by the object specified in the synchronized statement, one object only has a lock, after being obtained by a thread, it is not Have this lock, the thread will receive the lock back to the object after executing the SYNCHRONIZED statement. A method can declare a method as a synchronization method in front of the method before the method. The synchronization method gets a lock before execution. If this is a class method, the obtained lock is the lock of the Class class object related to the class of the declaration method. If this is an instance method, then this lock is the lock of the THIS object.
Let's talk about some common methods:
Wait (), WAIT (), NOTIFY (), NotifyAll (), etc. is the instance method of the current class. Wait () is a thread release lock that enables the object lock; Wait (long) is to lock the object lock After the thread release lock time is long (millisecond), get the lock again, Wait () and Wait (0) equivalence; notify () is a thread that is awakening a waiting object lock, if the waiting thread is not only one, then wake up The thread is determined by JVM; NotifyAll is a thread that wakes all waiting object lock. Here I also reiterate, we should use the notifyAll () method, because wake-up all threads are easier to get the JVM to find the most suitable Wake-up threads. For the above method, only in the current thread can be used, otherwise the runtime error java.lang.illegalmonitorstateException: Current Thread Not Owner.
Below, I am talking about the relationship between SYNCHRONIZED and WAIT (), Notify ():
1. There is not necessarily WAIT, Notify, NOTIFY
2. There is Wait, Notify, you must have synchronized. This is because Wait and Notify are not a thread class, but every object has a method, and both methods are related to the object lock, locked place, There must be synchronized.
Also, please note: If you want to put the Notify and Wait methods, you must call NOTIFY to call Wait, because if you call Wait, the thread is no longer Current Thread. Such examples:
/ ** * Title: JDeveloper's Java ProjDect * Description: N / A * Copyright: Copyright (c) 2001 * Company: SOHO http://www.chinajavaworld.com * @Author jdeveloper@21cn.com * @version 1.0 * / Import java.lang.Runnable; import java.lang.thread;
Public class demothread implements runnable {
Public demothread () {Testthread Testthread1 = New Testthread (this, "1"); testthread testthread2 = new testthread (this, "2");
TestthRead2.start (); testthread1.start ();
}
Public static void main (string [] args) {demothread demothread1 = new demothread ();
}
Public void run () {
Testthread T = (Testthread) thread.currentthread (); try {if (! T.getname (). EqualsignoreCase ("1")) {synchronized (this) {wait ();}} while (true) {
System.out.println ("@ Time in Thread" T.GetName () "=" T.Increasetime ()); if (t.gettime ()% 10 == 0) {synchronized (this) {system .out.println ("********************************************************************************************************************"); Notify (); If (t.gettime () == 100) Break; Wait ();}}}} catch (exception e) {E.PrintStackTrace ();}}
}
Class testthread extends thread {private int today = 0; public testthread (Runnable R, String Name) {Super (r, name);}
Public int gettime () {return time;}
Public int increasetime () {return time;}
}
Below we use the producer / consumer example to explain the relationship between them:
Public class test {public static void main (STRING ARGS []) {semaphore s = new semaphore (1); thread t1 = new thread (s, "produter1"); thread t2 = new thread (s, "produter2"); Thread T3 = New Thread (S, "Producer3"); Thread T4 = New Thread (S, "Consumer1"); Thread T5 = New Thread (S, "Consumer2"); Thread T6 = New Thread (s, "consumer3" ); T1.start (); t3.start (); t4.start (); t5.start (); t6.start ();}}
Class Semaphore Implements Runnable {Private Int Count; Public Semaphore (INT N) {this.count = n;
Public synchronized void acquire () {while (count == 0) {Try {Wait ();} catch (interruptedException e) {// Keep trying}} count-;
public synchronized void release () {while (count == 10) {try {wait ();} catch (InterruptedException e) {// keep trying}} count ; notifyAll (); // alert a thread that's blocking on this semaphore } public void Run () {while (true) {if (thread.currentthread (). getname (). Substring (0,8) .EqualsignoreCase ("consumer") {acquire ();} else if (thread.currentthread () .GETNAME (). Substring (0, 8). Equalsignorecase ("producer")) {release ();} system.out.println (thread.currentthread (). getname () "" count);} }
Production, consumer consumption, generally there is no conflict, but when inventory is 0, consumers should not consumption, but when stocks are the upper limit (here 10), the producer can not be produced. Please study the above Procedure, you will have a lot more than before.
The above code illustrates Synchronized and Wait, Notify has no absolute relationship, in the method of synchronized declaration, code block, you can do it without Wait, Notify, etc., however, if threads have some kind of contention In case, you must put the thread in a wait or wake up.
The article finally finished, basically written all my learning, but also left a little regret, such as Synchronized is a deep explanation and discussion of the class. Moreover, due to the limited ability, some places will definitely have errors. I hope that what suggests and criticism, please post below, I will fix the article. Thank you!