Java multi-thread support (1)-Thread class, runnable interface, daemon thread, thread synchronization

Source: Internet
Author: User

Java is the firstLanguages that support multi-threaded programming are provided at the language level. What does language-level support mean? Aside from the operating system, you can use only the built-in JAVA statements to implement multithreading. Generally, multithreading depends on the operating system. We need to use system-related APIs to create multiple threads, such as the createthread () function in windows. But JAVA does not. Java runtime systemA thread scheduler used to call thread execution is implemented to determine which thread runs on the CPU at a certain time point..

In Java technology, threads are usuallyPreemptible without the need for time slice allocation process(Processes allocated to each thread for equal CPU time ). The preemptible scheduling model means that many threads are running (waiting), but only one thread is running. This thread runs until it is terminated and enters the runable state (waiting state), or another thread with a higher priority changes to the runable state. In the latter case, low-priority threads are preemptible by high-priority threads, and high-priority threads get the chance to run. LineThe scheduler supports preemptive scheduling of threads with different priorities, but does not support time slice rotation of threads with the same priority. To support this function, you must run the runtime system on the operating system that supports time slice rotation..

1. Thread class and runnable interface

There are two ways to implement multithreading in Java:Inherit Thread classAnd the other isImplement the runnable interface. Because Java does not allow many inheritance, we cannot inherit other classes when we make the custom class inherit the Thread class, which will reduce the scalability of future programs. Therefore, we generally use runnable interfaces to make a class executable.

The runnable interface has only one run () method. When the thread starts, JVM will call the run () method to execute this thread. After a Thread class is created, the START () method must be called to start the thread. For example:

Package CLS; public class threaddemo {public static void main (string [] ARGs) {// create a thread Class Object and implement the runnable interface thread Th1 = new thread (New runnable () {// implement the run () method public void run () {While (true) system in runnable. out. println ("thread1 is running! ") ;}}); Thread Th1 = new thread (New runnable () {public void run () {While (true) system. Out. println (" thread2 is running! ") ;}}); // Call the START () method to start the thread th1.start (); th2.start ();}}

2. daemon thread

A daemon thread refers toThe thread that executes the service in the background.. When executing the code in the previous example, we found that when the main thread (main function) executes the th2.start () line, the code of the main thread has been fully executed, therefore, the main thread exits. But we can see thatThe two threads created by myself, Th1 and 2nd, are still being executed and are not exited.. If we want the created thread to exit after the main function exits, we should set the thread we created to daemon.The daemon thread automatically exits when all non-daemon threads are finished..

Let's modify the previous example:

Package CLS; public class threaddemo {public static void main (string [] ARGs) {// create a thread Class Object and implement the runnable interface thread Th1 = new thread (New runnable () {// implement the run () method public void run () {While (true) system in runnable. out. println ("thread1 is running! ") ;}}); Thread Th1 = new thread (New runnable () {public void run () {While (true) system. Out. println (" thread2 is running! ") ;}}); // Set to daemon thread th1.setdaemon (true); th2.setdaemon (true); // call the START () method to start thread th1.start (); th2.start (); // main function sleep for a short time try {thread. currentthread (). sleep (200);} catch (exception e) {system. out. println (E. tostring ());}}}

After running, we can see that the main thread exits after ms, and the corresponding Th1 and 22.

3. Thread Synchronization

Assume that object A has two attributes a and B, and another object B has attributes a and B, and we will use object B to update object. After the update operation is completed (the attribute values of A and B of object a are changed to the attribute values of A and B of object B), A and B are synchronized.

If object B comes to object C when updating object A (not updated yet), and Object C updates object a before object B, it is said that A and B are not synchronized.

Thread Synchronization has to be considered when discussing threads. When multiple threads share the same data, data synchronization may occur. Errors Caused by non-synchronization are often hard to be corrected, and often occur when the program is executed thousands of times, tens of thousands of times, or even several years. Therefore, thread synchronization is particularly important.

The following is an example of a simulated train station ticket sales, which deliberately causes the thread to be out of sync to see what will happen:

Package CLS; public class threadsynchronized {public static void main (string [] ARGs) {ticket TK = new ticket (); thread Th1 = new thread (New sold (TK )); thread Th1 = new thread (New sold (TK); th1.start (); th2.start () ;}} class ticket {int amount = 100; // There are 100 tickets // sell one ticket, the total number of votes minus 1, return the sold ticket number public int sold () {return amount --;} // return the remaining number of votes currently public int getamount () {return amount ;}// ticket selling Thread class sold implements runnable {private ticket TK; Public sold1 (ticket tk) {This. TK = TK;} public void run () {While (TK. getamount ()> 0) // there are remaining votes {try {thread. currentthread (). sleep (10); // sleep for a short time} catch (exception e) {system. out. println (E. tostring ();} system. out. println ("thread1 sold" + TK. sold ());}}}

Run:

We found that the thread thread1 actually sold the zero ticket that does not exist. The ticket sales thread has done this before selling tickets.

tk.getAmount() > 0

I have determined why I still sell 0 of the tickets?

Let's analyze the Program Execution Process:

When there is still one ticket, thread1 uses getamout () to determine that the number of votes is greater than 0, and then enters the while loop to sell tickets. If you encounter sleep () before selling it, thread1 will give up the execution opportunity and enter the blocking state. At this time, thread2 is executed, because thead1 has not sold 1, therefore, the result of using getamout () for thread2 is still greater than 0, so I sold the 1 ticket. When thread1 wakes up, it continues to run from sleep (), and the number of votes has changed to 0, then thead1 will naturally sell the 0 votes.

To avoid this, we can use the synchronized keyword for thread synchronization.

The synchronized keyword can be used in methods or statement blocks. We can visually think of synchronized as a lock. When the program executes the synchronized statement block (later called the synchronization block), the Code of the synchronization block is "locked". If we call sleep () the method or the time slice allocated by the CPU is used up. If the code is to be executed by another thread, because the previous thread has locked the synchronization block ", therefore, this thread cannot execute the code in the synchronization block and can only wait until its time slice is used up. At this time, the previous thread got the opportunity to execute the code block. After the code block is executed, it will "unlock" the code block so that other threads can execute the code block. That is to say, a synchronization block can only be executed by a specific thread within a period of time. Before the thread does not execute the Statement of the code block, other threads cannot execute the code in this block. Java implements this function by requesting the monitor of an object. An object has only one monitor. When a thread requests an object, the other thread cannot request the object's monitor before the thread returns the (synchronous block execution) Monitor.

Now let's rewrite the above example:

Package CLS; Class threadsynchronized {public static void main (string [] ARGs) {ticket TK = new ticket (); sold SD = new sold (TK ); thread Th1 = new thread (SD); thread Th1 = new thread (SD); th1.start (); th2.start () ;}} class ticket {int amount = 100; // There are 100 tickets // sell one ticket, the total number of votes minus 1, return the sold ticket number public int sold () {return amount --;} // return the remaining number of votes currently public int getamount () {return amount ;}// ticket selling Thread class sold implements runnable {private ticket TK; Public sold (ticket tk) {This. TK = TK;} public void run () {While (true) {// synchronous statement block synchronized (this) // request this object's monitor {If (TK. getamount ()> 0) {try {thread. currentthread (). sleep (1); // sleep for a moment} catch (exception e) {system. out. println (E. tostring ();} system. out. println (thread. currentthread (). getname () + "sold" + TK. sold ());}}}}}

As you can see, the problem is solved.

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.