Java multi-threaded learning notes (1)
Author: cultivate (innocent) Time: 2003.6.18
First, the threaded Java is a multi-thread, the first Thread object describes a separate thread through the Java.lang.Thread class. To generate a thread, there are two ways: 1, you need to inherit a new thread class from the java.lang.Thread class, overloading its Run () method; 2. Implement an inheritance from non-thread class through the Runnalbe interface Multi-threaded, overloaded Run () methods of the Runnalbe interface. Running a new thread, just calling its start () method. Such as: / ** ============================================== ======================== * file: threadDemo_01.java * Description: Generate a new thread * =========== ============================================================================================================================================================================================================= ========= * / Class ThreadDemo Extends thread {threads () {} threads (String Szname) {super (szname);} // Reserved Run function public void run () {for (int count = 1, row = 1; ROW <20; ROW , Count ) {for (int i = 0; i Class threadmain {public static void main (string argv []) {threadDemo th = new threadDemo (); // Call the start () method Perform a new thread th.Start ();}} Some common methods for thread classes: Sleep (): Forced a thread sleep N milliseconds. Isalive (): Judging whether a thread survives. Join (): Wait for thread to terminate. ActiveCount (): The number of active threads in the program. ENUMERATE (): Enumerates the thread in the program. CurrentThread (): Get the current thread. Isdaemon (): Whether a thread is a daemon. SetDaemon (): Sets a thread as a daemon. (The difference between the user thread and the daemon is to end if the main thread is ended on the end of the main thread.) SetName (): Sets a name for the thread. Wait (): Forced a thread waiting. Notify (): Informs a thread to continue running. SetPriority (): Sets a thread priority. Second, waiting for a thread to run another thread after running our thread, then what should we do? Please see the example below: / ** ========================================= ============================ * file: threadDemo_02.java * Description: Waiting for a thread * ======= ============================================================================================================================================================================================================= ============= * / Class ThreadDemo Extends thread {threads () {} threads (SZNAME) {super (szname);} // overload Run function public void run () {for (int count = 1, row = 1; ROW <20; ROW , count ) {for (int i = 0; i Class threadmain {public static void main (string argv []) {// generates two same thread threadDemo th1 = new threadDemo (); threaddemetero th2 = new threadDemo (); // Our goal is to run the first thread, then run the second thread th1.start (); th2.Start ();}} Our goal is to first run the first thread, wait for the first one After the thread is terminated, run the second thread again, and what is the result of the actual run? In fact, the results of our run are not the right triangles we want, but some messy * rows, some long, some short. Why is this so? Because the thread does not perform in accordance with our call order, it produces a thread race. In fact, Java cannot perform threads in our call order, which also shows that the thread is a separate code executed in parallel. If you want to get our expected results, we need to judge whether the first thread has terminated, if it has been terminated, then call the second thread. The code is as follows: / ** ============================================== ========================== * file: threadDemo_03.java * Description: Two methods waiting for a thread ended * ====== ============================================================================================================================================================================================================= ============== * / Class threadDemo extends thread {threads () {} threads (SZNAME) {super (szname);} // Reserved Run function public void Run () { For (int count = 1, row = 1; ROW <20; Row , Count ) {for (int i = 0; i Class threadmain {public static void main (string argv []) {threadmain test = new threadmain (); test.method1 (); // Test.Method2 ();} // First method: Continuously querying whether the first thread has terminated, if not, let the main thread sleep until it terminates // ie: while / isalive / sleep public void method1 () {threadDemo th1 = new threadDemo (); ThreadDemo TH2 = New ThreadDemo (); // Execute the first thread th1.Start (); // Continuously query the status of the first thread While (th1.Isalive ()) {Try {thread.sleep (100 );} Catch (interruptexception e) {}} // The first thread is terminated, running the second thread th2.start ();} // second method: join () public void method2 () {threadDemo th1 = New threadDemo (); threadDemo th2 = new threadDemo (); // Perform the first thread th1.Start (); try {th1.join ();} catch (interruptedException e) {} // execute the second thread TH2 .Start ();} three, thread synchronization problems Sometimes, we need a lot of threads to share a piece of code, such as a private member or a static member in a class, but because of the problem of thread racing, we get the right output result, and the opposite is often Zhang Guan Li Dai, with us The expected results are different. Look at the example below: / ** =========================================== ============================================= * file: threadDemo_04.java * Description: Multi-thread is not synchronized * =========================================================================================================================================================================================== =================================// Share a static data object class sharedata {public static string szdata = "} Class threadDemo extends thread {private sharedata {}1addemo () {} ThreadDemo (String Szname, Sharedata Oshare) {Super (Szname); this.oshare = OSHARE;} Public void run () {// In order to see incorrect results more clearly, put a large cycle for (INT i = 0; i <50; i ) {if (this.getname (). Equals. Thread1 ")) {OSHARE.SZDATA =" This is the first thread "; // To demonstrate the problem, set a sleep try {thread.sleep (int) math.random () * 100); catch ( InterruptedException E) {} // Output System.out.println (this.getname () ":" OSHARE.SZDATA); Else IF (this.getname (). Equals ("thread2") {oshare. SZDATA = "This is the first thread"; // To demonstrate the problem, set a sleep try {thread.sleep (INT) math.random () * 100); Catch (InterruptedException E) {} // Output System.out.println (this.getname () ":" OSHARE.SZDATA);}}} class ThreadMain {public static void main (String argv []) {ShareData oShare = new ShareData (); ThreadDemo th1 = new ThreadDemo ( "Thread1", oShare); ThreadDemo th2 = new ThreadDemo ( "Thread2", oShare); TH1.Start (); th2.start ();}} Since the thread is running, the result of the output is often Thread1 corresponding to "This is the second thread", which is different from the results we have to output. In order to solve this problem (error), Java provides us with the "lock" mechanism to implement the synchronization of threads. The mechanism of the lock requires each thread to get the lock before entering the shared code, otherwise it will not be entered, and the lock is released before exiting the shared code, which prevents several or more threaded competition sharing code, which is solved. The problem of different walking threads. It can be said that when running a shared code, there is only one thread to enter, which is the monopoly we say. The implementation method of the lock mechanism is to join the SYNCHRONIZED segment before sharing code, and the shared code is included in the Synchronized segment. The solution to the above problem is: / ** =========================================================================================================================================================================== ======================================= * file: threadDemo_05.java * Description: Multi-threaded disagreement solution - lock * ============================================================================================================================================================================================================= ====================================// Shared a static data object class sharedata {public static string szdata = "";} Class ThreadDemo Extends thread {private sharedata oshare; ThreadDemo () {} ThreadDemo (String Szname, Sharedata Oshare) {Super (Szname); this.oshare = OSHARE;} Public void run () {// In order to see incorrect results more clearly, put a large cycle for (INT i = 0; i <50; i ) {if (this.getname (). Equals. Thread1 ")) {// Lock OSHARE Sharing Object Synchronized (OSHARE) {OSHARE.SZDATA =" This is the first thread "; // To show the problem, you set a sleep try {thread.sleep ((int) Math.random () * 100); Catch (InterruptedException E) {} // output result system.out.println (this.getname () ":" OSHARE.SZDATA);}} else f (this.getname ) .Equals ("thread2")) {// Lock Sharing Object Synchronized (OSHARE) {oshare.szdata = "This is the first thread"; // To show the problem generated, set a sleep try {thread.sleep (INT) Math.random () * 100); Catch (InterruptedException E) {} // Output System.out.Println (this.getname () ":" OSHARE.SZDATA);}}}} Threadmain {public static void main (string argv []) {sharedata oshare = new sharedata (); threadDemo th1 = new threadDemo ("Thread1 ", oshare); ThreadDemo TH2 = New ThreadDemo (" Thread2 ", OSHARE); TH1.Start (); th2.Start ();}} Due to excessive Synchronized segments will affect the running efficiency of the program, the synchronization method is introduced, and the implementation of the synchronization method is to write the shared code in one method, Add the synchronized keyword before the method. There are two problems that need to be aware of when thread synchronization: 1. No synchronization problem: 2, deadlock problem: that is, the two threads caused by the two or more threads cannot get the corresponding locks. This phenomenon is mainly due to the nesting Synchronized code segment, so it is a good way to prevent thread dead locks as little as possible in the program. A problem that I can't solve the above code, I will take it here, I hope everyone is discussing. / ** =========================================================================================================================================================================== ======================================= * file: threadDemo_06.java * Description: Why causing the thread different from step. * =========================================================================================================================================================================================== ============================= * / Class ThreadDemo Extends thread {// Share a static data member private static string szsharedata = "" ThreadDemo () {} ThreadDemo (String Szname) {super (szname); Public void run () {// In order to see incorrect results more clearly, put a large cycle for (INT i = 0; i <50; i ) {if (this.getname (). Equals. ") {Synchronized (szsharedata) {szsharedata =" This is the first thread "; // To demonstrate the problem, set a sleep try {thread.sleep ((int) math.random () * 100) Catch (InterruptedException E) {} // Output Results System.out.Println (this.getname () ":" szsharedata);}} else if (this.getname (). Equals ("thread2)) { Synchronized (Szsharedata) {szsharedata = "This is the first thread"; // To demonstrate the problem, set a sleep try {thread.sleep (INT) math.random () * 100); Catch (InterruptedException E ) {} // output system.out.println (this.getname () ":" szsharedata);}}}} Class threadmain {public static void main (string argv []) {threadDemo th1 = new threadDemo "Thread1"); ThreadDemo TH2 = New ThreadDemo ("Thread2"); TH1.Start (); th2.start ();}} The shared member of this code is a static member in a class. It is reasonable that the lock you get when you enter the shared code should be the same lock, but the input of the above program is not synchronized, why? ? Reference: << Strong performance with thread >>