Java multithreading simple case study

Source: Internet
Author: User

This article introduces three points:

1. Comparison of Single-thread and multi-thread

2. Two Methods for creating multithreading: 1. extends Thread 2. implements Runnable

Iii. Thread Synchronization


1. Comparison of Single-thread and multi-thread

1. Single thread

TestThread. java

public class TestThread {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubnew ThreadDemo().run();while(true){System.out.println("main():"+Thread.currentThread().getName());}}}class ThreadDemo{public void run(){while(true){System.out.println("run():"+Thread.currentThread().getName());}};}

Running result:

Result Analysis: in fact, this is only a common single-threaded program, so the while () code in the main () method will not be executed. In addition, new ThreadDemo (). run (); is run in the main thread.

2. multithreading (Change TestThread. java to a multithreading and compare the running results)

TestThread2.java

public class TestThread2 {public static void main(String[] args) {// TODO Auto-generated method stubnew ThreadDemo2().start();while(true){System.out.println("main():"+Thread.currentThread().getName());}}}class ThreadDemo2 extends Thread{public void run(){while(true){System.out.println("run():"+Thread.currentThread().getName());}};}

Running result:

Analysis result: the ThreadDemo2 thread and main thread are executed alternately and unordered.

Keep up with TestThread. java comparison, two differences: 1. testThread. threadDemo in java is not a Thread, because there is no extends Thread and there is no implements Runnable, so TestThread. java is a common single-threaded program. ThreadDemo2 in TestThread is a Thread, because the start Thread method of extends Thread. 2 and ThreadDemo2 is start (), not run ().

Bytes -----------------------------------------------------------------------------------------------------------

2. Two Methods for creating multithreading: 1. extends Thread 2. implements Runnable


1). Use the Thread class to create a Thread

1. To run a piece of code on a new Thread, the code should be in the run () function of the class, and the class where the run () function is located is the subclass of the Thread. To implement multithreading, you must compile a subclass that inherits the Thread class. The subclass must overwrite the run () function in the Thread class and run () function in the subclass () the function calls the program code that you want to run on the new thread.

2. start the thread. The start () method is required instead of the run () method.

3. Because the code segment of the thread is in the run method, the thread will end the response after the method is executed. Therefore, you can control the end of the thread by controlling the loop conditions in the run method.

1) Foreground thread, daemon thread (also called background thread) and federated thread

1. If the setDaemon (true) method is called before a thread object is started (the start method is called), the thread becomes a daemon thread.

2. For java programs, as long as there is another front-end thread running, this process will not end; if a process only has a daemon thread running, this process will end. '

3. pp. join () is used to merge the threads corresponding to pp into the threads that call pp. join (); statements.

3.1 TestThread3.java

public class TestThread3 {public static void main(String[] args) {// TODO Auto-generated method stubnew ThreadDemo3().start();}}class ThreadDemo3 extends Thread{public void run(){while(true){System.out.println("run():"+Thread.currentThread().getName());}};}

Running structure:

Program analysis: the main () method executes new ThreadDemo3 (). start (); after this statement, the main method ends, that is, the main thread of the main method ends. Note: although the main thread is finished, the java program is not finished because ThreadDemo3 is still being executed. Description of this program: In a java program, as long as there is another front-end thread running, the java program will not end (although the main thread has ended ).


3.2 TestThread4.java

Public class TestThread4 {public static void main (String [] args) {// TODO Auto-generated method stubThread tt = new ThreadDemo4 (); tt. setDaemon (true); // sets the thread as the daemon tt. start () ;}} class ThreadDemo4 extends Thread {public void run () {while (true) {System. out. println ("run ():" + Thread. currentThread (). getName ());}};}

Running result:


Program Result Analysis: ThreadDemo4 is the daemon thread. java ends immediately when only the daemon thread is in the java program.


4. TestThread5.java (meaning of parsing tt. join (), tt. join (10000)

public class TestThread5 {public static void main(String[] args) {ThreadDemo5 tt = new ThreadDemo5();tt.start();int index = 0 ;while(true){if (index ++ == 100) {try {tt.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println("main():"+Thread.currentThread().getName());}}e.printStackTrace();}class ThreadDemo5 extends Thread{public void run(){while(true){System.out.println("run():"+Thread.currentThread().getName());}};}

Program Analysis:

1. tt. join (). the running result is: The ThreadDemo5 tt thread and the main thread run alternately at the beginning. When the index of the main thread reaches 100. join indicates that the tt thread is added to the main thread, that is, the tt thread and the main thread are merged into a new single thread. The program running result is: thread-0 at the beginning, alternating main. When the index of the main thread reaches 100, it is until the end of thread-0. When the index of the main thread reaches 100, the tt thread is added to the main thread and becomes a single thread. Therefore, when the tt thread is executed, the main thread will not be executed until the tt thread is executed.

2. tt. join (1, 10000 ). the running result is: at the beginning, the tt thread and the main thread run alternately. When the index of the main thread reaches 100, the tt thread joins the main thread to become a new single thread (10 seconds ), after 10 seconds, the tt thread and main thread become separate threads again to form the beginning of multithreading. Tt. join (10000) indicates that the tt thread is added to the main thread to form a new single thread for 10 seconds.


(2) create a thread by implementing the Runnable interface

Class ThreadDemo {public void run (){}};

Main () {Thread tt = new Thread (new ThreadDemo (); tt. start ();}

3) differences between the two methods for creating threads

Eg: 100 tickets are sold at the railway station in four windows. Compare the differences between using extends Thread and implements Runnable.

Comparison results: Runnable is recommended. implements Runnable is recommended for almost all programs that require multithreading.

1. With extends Thread, java programs will use one thread by default to sell tickets.

2. When implements Runnable is used, the java program will automatically call four threads to sell tickets.

4.1 TestThread6.java

package com.thread;public class TestThread6 {public static void main(String[] args) {new ThreadDemo6().start();new ThreadDemo6().start();new ThreadDemo6().start();new ThreadDemo6().start();}}class ThreadDemo6 /*implements Runnable*/ extends Thread{int tickets = 100 ;public void run(){while(tickets>0){//if(tickets>0){System.out.println("run():"+Thread.currentThread().getName()+"is saling ticket "+tickets--);}}};}

Running result: each of the four threads sells 100 tickets.

4.2 TestThread7.java

package com.thread;public class TestThread7 {public static void main(String[] args) {ThreadDemo7 t = new ThreadDemo7();new Thread(t).start();new Thread(t).start();new Thread(t).start();new Thread(t).start();}}class ThreadDemo7 implements Runnable{int tickets = 100 ;public void run(){while(tickets>0){//if(tickets>0){System.out.println("run():"+Thread.currentThread().getName()+"is saling ticket "+tickets--);}}};}

Running result:


Bytes ---------------------------------------------------------------------------------------------------------------------------

Iii. Thread Synchronization

Thread Synchronization Method: Use synchronized to perform atomic operations on code blocks that require thread security.

Let's take a look at a piece of thread-Insecure code, taking 100 tickets as an example. In this example, if four threads sell 100 tickets, both 0 and negative numbers may be printed. Normally (100 ~ 1 ).

The cause of the exception is that when thread 1 executes the while (tickets> 0) sentence, tickets = 1, then the operating system suddenly switches to thread 2 (thread 1 does not execute system. out. print (tickets --), thread 2 judges tickets = 1 at this time, and prints "sell ticket 1", tickets -- changes to 0, at this time, the operating system switches to thread 1 to continue executing the system. out .... (tickets --), print "0 sold tickets ". Similarly, if "while (tickets> 0)" is executed before thread 3, tickets = 2 at that time, and system is not executed yet. the out () Statement is switched by the operating system, and later it is switched to thread 3 to execute the system. out. in print (tickets --), tickets may have changed to-1 at the time. Therefore, thread 3 prints "sell ticket-1". Similarly, you can exit and print "sell ticket-2.

Cause analysis:

Because the while (tickets> 0) statement is not synchronized with the code block {system. out. println (tickets --)} in the loop body. That is, the while (tickets> 0) and {system. out. println (tickets --)} code block operations should be kept atomic.

Note: The Thread. sleep (10) statement is only used to simulate Thread insecurity. Without this statement, the program is also Thread insecure.

5.1 TestThread8.java

Package com. thread; public class TestThread8 {public static void main (String [] args) {ThreadDemo8 t = new ThreadDemo8 (); new Thread (t ). start (); new Thread (t ). start (); new Thread (t ). start (); new Thread (t ). start () ;}} class ThreadDemo8 implements Runnable {int tickets = 100; public void run () {while (tickets> 0) {/* thread sleep for 10 milliseconds, simulate thread insecurity. If you do not add sleep (), the thread is not secure. If you add sleep (), unsafe results are more likely to appear. */Try {Thread. sleep (10);} catch (Exception e) {e. printStackTrace () ;}; System. out. println ("run ():" + Thread. currentThread (). getName () + "is saling ticket" + tickets --);}}}

Result:


To ensure the atomicity of the while (tickets> 0) and {system. out. println (tickets --)} code block operations, use synchronized (object.

5.2 TestThread9.java

Package com. thread; public class TestThread9 {public static void main (String [] args) {ThreadDemo9 t = new ThreadDemo9 (); new Thread (t ). start (); new Thread (t ). start (); new Thread (t ). start (); new Thread (t ). start () ;}} class ThreadDemo9 implements Runnable {int tickets = 100; String str = ""; public void run () {synchronized (str) {/* synchronized (any object) code blocks can be atomic */while (tickets> 0) {// threads sleep for 10 milliseconds, simulating thread insecurity. If you do not add sleep (), the thread is not secure. If you add sleep (), unsafe results are more likely to appear. Try {Thread. sleep (10);} catch (Exception e) {e. printStackTrace () ;}; System. out. println ("run ():" + Thread. currentThread (). getName () + "is saling ticket" + tickets --);}}}}

Running result:

Note: with synchronized (any object name) {code block}, you can perform code block atomic operations to ensure code block synchronization. Because each object has a flag, 0 or 1.

When the str flag is 1, the thread enters the code block. The str flag immediately changes to 0 and becomes blocked. Other threads are blocked. Only after the synchronized code block is executed and the str flag bit changes to 1 will the blocking state be canceled and the java program can be switched to other threads for execution.

The flag of str is also called the lock flag of the monitor.

When other threads access the str monitor, if the lock flag of the str monitor is 0, other threads will enter a waiting thread pool generated by the str monitor's flag lock. The lock flag of the str monitor is only available when the lock flag of the str monitor is changed to 1.

Note: String str = ""; must be placed outside the run () method.

You can also use the synchronization function to achieve the synchronization effect. Check the Code:

5.3 TestThread10.java

Package com. thread; public class TestThread10 {public static void main (String [] args) {ThreadDemo10 t = new ThreadDemo10 (); new Thread (t ). start (); new Thread (t ). start (); new Thread (t ). start (); new Thread (t ). start () ;}} class ThreadDemo10 implements Runnable {int tickets = 100; String str = ""; public void run () {sale ();} public synchronized void sale () {while (tickets> 0) {// The thread sleep for 10 milliseconds, simulating thread insecurity. If you do not add sleep (), the thread is not secure. If you add sleep (), unsafe results are more likely to appear. Try {Thread. sleep (10);} catch (Exception e) {e. printStackTrace () ;}; System. out. println ("run ():" + Thread. currentThread (). getName () + "is saling ticket" + tickets --);}}}

Note: If the synchronized keyword is added before the method name, the sale () method is thread-safe and the monitor is the this object.

You can use the synchronous code block to synchronize between threads, or use a synchronous function to synchronize between threads.

How can I keep the synchronization code block and the synchronization function synchronized? Use the same monitor this. See the following program.

5.4 TestThread11.java

Package com. thread; public class TestThread11 {public static void main (String [] args) {ThreadDemo11 t = new ThreadDemo11 (); new Thread (t ). start (); try {Thread. sleep (1);} catch (Exception e) {e. printStackTrace ();} t. str = "method"; new Thread (t ). start () ;}} class ThreadDemo11 implements Runnable {int tickets = 100; String str = ""; public void run () {if (str. equals ("method") {sale ();} else {synchronized (th Is) {while (tickets> 0) {// The thread sleep for 10 milliseconds, simulating thread insecurity. If you do not add sleep (), the thread is not secure. If you add sleep (), unsafe results are more likely to appear. Try {Thread. sleep (10);} catch (Exception e) {e. printStackTrace () ;}; System. out. println ("run ():" + Thread. currentThread (). getName () + "is saling ticket" + tickets --) ;}}} public synchronized void sale () {while (tickets> 0) {// thread sleep for 10 milliseconds, simulate thread insecurity. If you do not add sleep (), the thread is not secure. If you add sleep (), unsafe results are more likely to appear. // Try {Thread. sleep (10);} catch (Exception e) {e. printStackTrace () ;}; System. out. print ("sale-"); System. out. println ("run ():" + Thread. currentThread (). getName () + "is saling ticket" + tickets --);}}}

Note:How to synchronize code blocks and synchronous functions: Share a monitor with them.In this example, the common monitor is this object and cannot be str. Because the monitor of the synchronous function is this object, the monitor of the synchronous code block must also be this object. Synchronized (this) is correct. If it is written as synchronized (str), the synchronization code block and the synchronization function cannot be synchronized.


Please refer to: http://www.iqiyi.com/w_19rr799759.html ?######

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.