Multi-threading and multi-process (3) multithreading in the "turn" programming idea--java

Source: Internet
Author: User
Tags thread class ticket

"Multi-threading and multi-process (1)--talking about threads and processes from the perspective of an operating system" describes in detail the threads, process relationships, and performance in the operating system, which must be understood as a basis for multithreaded learning. This article goes on to talk about the development of multi-threaded software in Java

Single Thread

Any program that has at least one thread, even if you do not actively create a thread, the program executes from the beginning with a default thread, called the main thread, and a single threaded program is called a multithreaded procedure. As in the following simple code, a thread is created without a display, the program executes from main, and main itself is a thread (the main thread), and a single thread executes from the beginning to the end.

"Demo1": Single threaded

public static void Main (String args[]) {   System.out.println ("output number from 1 to 100:");   for (int i = 0; i <; i + +) {      System.out.println (i + 1);   }}

Creating Threads

Single-threaded applications are straightforward but sometimes do not meet specific needs. such as a word processing program, I print the article at the same time to be able to edit the text, if it is a single-threaded program to wait for the printer after printing you can edit the text, but the printing process is generally relatively long, which we can not tolerate. If multi-threading is used, the main thread can continue to edit the text while printing by opening threads individually. Multithreading can be used when a program needs to perform multiple tasks simultaneously.

Multithreading can be used when a program needs to perform multiple tasks simultaneously. Java provides built-in support for multithreaded programming, providing two ways to create threads: 1. By implementing the Runable interface; 2. By inheriting the thread class.

Thread is a thread-supported class implemented by the JDK, and the thread class itself implements the Runnable interface, so runnable is the interface that the creation thread must implement; Runnable has only one run method, so you must implement the Run method regardless of how you create the thread. We can look at an example.

"Demo2": Creation and use of threads

/** * Created with IntelliJ idea. * User:luoweifu * date:15-5-24 * Time: p.m. * To change this template use File | Settings | File Templates.   *//** * By implementing the Runnable method */class Threada implements Runnable {private thread thread;   Private String ThreadName;      Public Threada (String threadname) {thread = new thread (this, threadname);   This.threadname = ThreadName; }//Implement the Run method public void run () {for (int i = 0; i <; i + +) {System.out.println (ThreadName + ":"      + i);   }} public void Start () {Thread.Start ();   }}/** * method of inheriting thread */class THREADB extends thread {private String threadname;      Public threadb (String threadname) {super (threadname);   This.threadname = ThreadName; }//Implement the Run method public void run () {for (int i = 0; i <; i + +) {System.out.println (ThreadName + ":"      + i); }}}public class multithread{public static void Main (String args[]) {Threada Threada = new Threada ("Threada");      THREADB threadb = new Threadb ("threadb");      Threada.start ();   Threadb.start (); }}

Description: The example above illustrates two ways to implement threads. In most cases, it is preferable to implement the Runnable interface in a way that inherits the thread, because:
1. Inheriting from the Thread class imposes class hierarchies;
2. Some classes cannot inherit the thread class, such as if the class to run as a thread is already a subclass of a class, but Java only supports single inheritance, so it is no longer possible to inherit the thread class.

Thread synchronization

There are several types of relationships between threads and threads:

Model One : simple threads, multiple threads executing at the same time, but the tasks handled by each thread are irrelevant, no data and resources are shared, and there is no scramble for resources. In this case, regardless of how many threads are executing at the same time are safe, the execution model is as follows:


Figure 1: Handling Independent tasks

model two : complex threads, where multiple threads share the same data or resources, can cause multiple threads to scramble for a resource. At this point it is easy to cause unexpected (error) processing of the data, which is thread insecure and its model is as follows:


Figure 2: Multiple threads sharing the same data or resources

In the case of model two, it is necessary to consider thread synchronization to ensure thread security. The most common way to support thread synchronization in Java is to add synchronized synchronization locks.

Let's look at an example of a thread-synchronous application.

Buy Fire Tickets is everyone's Spring Festival home the most concerned about things, we simply simulate the train ticket ticketing system (to make the program simple, we pull out the simplest model for simulation): There are 500 train tickets from Beijing to Ganzhou, sold in 8 windows at the same time, to ensure the stability of the system and data atomicity.


Figure 3: Analogue train ticket ticketing system

"Demo3": Train ticket ticketing system simulation program

/** * Class */class Service {private String ticketname of the emulated server;        Ticket name private int totalcount;        Total number of votes private int remaining;      Remaining votes public Service (String ticketname, int totalcount) {this.ticketname = Ticketname;      This.totalcount = TotalCount;   this.remaining = TotalCount;         } public synchronized int saleticket (int ticketnum) {if (Remaining > 0) {remaining-= Ticketnum;         try {//pause for 0.1 seconds to simulate time Thread.Sleep (100) for complex computations in the real system;         } catch (Interruptedexception e) {e.printstacktrace ();         } if (remaining >= 0) {return remaining;            } else {remaining + = Ticketnum;         return-1;   }} return-1;   } public synchronized int getremaining () {return remaining;   } public String Getticketname () {return this.ticketname;   }}/** * Ticketing procedure */class Ticketsaler implements Runnable {private String name;  Private service service; Public Ticketsaler (String windowname, service service) {this.name = Windowname;   This.service = Service;            } @Override public void Run () {while (service.getremaining () > 0) {synchronized (this) {            System.out.print (Thread.CurrentThread (). GetName () + "Sale" + service.getremaining () + "ticket,");            int remaining = Service.saleticket (1);            if (remaining >= 0) {System.out.println ("ticket issued successfully! Remaining" + remaining + "ticket."); } else {System.out.println ("Ticket failed! The ticket has been sold out.            "); }         }      }   }}

Test procedure:

/** * Test Class */public class Ticketingsystem {public   static void Main (String args[]) {      Service service = new Service ( "---Ganzhou, Beijing";      Ticketsaler Ticketsaler = new Ticketsaler ("Ticket procedure", service);      Create 8 threads to simulate 8 windows      thread threads[] = new Thread[8];      for (int i = 0; i < threads.length; i++) {         threads[i] = new Thread (Ticketsaler, "window" + (i + 1));         System.out.println ("window" + (i + 1) + "Start selling" + service.getticketname () + "ticket ...");         Threads[i].start ();}}}   

The results are as follows:

Window 1 began to sell Beijing –> Ganzhou ticket ...
Window 2 began to sell Beijing –> Ganzhou ticket ...
Window 3 began to sell Beijing –> Ganzhou ticket ...
Window 4 began to sell Beijing –> Ganzhou ticket ...
Window 5 began to sell Beijing –> Ganzhou ticket ...
Window 6 began to sell Beijing –> Ganzhou ticket ...
Window 7 began to sell Beijing –> Ganzhou ticket ...
Window 8 began to sell Beijing –> Ganzhou ticket ...
Window 1 sell the NO. 500 ticket, the ticket is successful! The remaining 499 tickets.
Window 1 sell the No. 499 ticket, the ticket is successful! The remaining 498 tickets.
Window 6 sell the No. 498 ticket, the ticket is successful! The remaining 497 tickets.
Window 6 sell the No. 497 ticket, the ticket is successful! The remaining 496 tickets.
Window 1 sell the No. 496 ticket, the ticket is successful! The remaining 495 tickets.
Window 1 sell the No. 495 ticket, the ticket is successful! The remaining 494 tickets.
Window 1 sell the No. 494 ticket, the ticket is successful! The remaining 493 tickets.
Window 2 sell the No. 493 ticket, the ticket is successful! The remaining 492 tickets.
Window 2 sell the No. 492 ticket, the ticket is successful! The remaining 491 tickets.
Window 2 sell the No. 491 ticket, the ticket is successful! The remaining 490 tickets.
Window 2 sell the No. 490 ticket, the ticket is successful! The remaining 489 tickets.
Window 2 sell the No. 489 ticket, the ticket is successful! The remaining 488 tickets.
Window 2 sell the No. 488 ticket, the ticket is successful! The remaining 487 tickets.
Window 6 sell the No. 487 ticket, the ticket is successful! The remaining 486 tickets.
Window 6 sell the NO. 486 ticket, the ticket is successful! The remaining 485 tickets.
Window 3 sell the No. 485 ticket, the ticket is successful! The remaining 484 tickets.
......

In the example above, the service class Saleticket method and the Ticketsaler class run method involving data changes are synchronized with the synchronized synchronization lock to ensure the accuracy and atomicity of the data.

For more detailed usage of synchronized see: "Synchronized usage in Java"

Line Program Control system

In multithreaded programs, in addition to the most important thread synchronization, there are other thread controls, such as thread interrupts, merges, priorities, and so on.

Thread Waits (wait, notify, Notifyall)

Wait: Causes the current thread to be in a wait state;
Notify: Wakes one of the waiting threads;
Notifyall: Wakes all waiting threads.

For detailed usage see: "Wait in Java Multi-threading, notify and Notifyall use"

Thread Break (interrupt)

In the thread support class thread provided by Java, there are three methods for threading interrupts:
public void interrupt (); The thread is disconnected.
public static Boolean interrupted (); is a static method that is used to test whether the thread has been interrupted and clears the interrupt state of the threads. So if the thread has been interrupted, it calls two times interrupted, and the second time returns false, because the interrupt state is cleared after the first return to true.
public boolean isinterrupted (); Tests whether the thread has been interrupted.

"Demo4": Application of Thread interruption

/** * Print thread */class Printer implements Runnable {public   void run () {while      (! Thread.CurrentThread (). isinterrupted ()) {     //If the current thread is not interrupted, perform a print job         System.out.println (Thread.CurrentThread ( ). GetName () + "print in ...");      if (Thread.CurrentThread (). isinterrupted ()) {         System.out.println ("interrupted:" +  thread.interrupted ());       Returns the status of the current thread and clears the status         System.out.println ("isinterrupted:" +  Thread.CurrentThread (). isinterrupted ());}      }   

Calling code:

Printer Printer = new Printer (); Thread printerthread = new Thread (printer, "Print thread");p Rinterthread.start (), try {   thread.sleep ();} catch ( Interruptedexception e) {   e.printstacktrace ();} System.out.println ("There is an urgent task that needs to interrupt the print thread."); System.out.println ("Status before Break:" + printerthread.isinterrupted ());p rinterthread.interrupt ();       Interrupt Print thread System.out.println ("State before Interrupt:" + printerthread.isinterrupted ());

Results:

Print threads in print ...
... ...
Print threads in print ...
There is an urgent task that needs to interrupt the print thread.
Print threads in print ...
Status before interrupt: false
Print threads in print ...
Status before interrupt: True
Interrupted:true
Isinterrupted:false

Thread merge (join)

The so-called merger is to wait for the other threads to execute, and then execute the current thread, as if the other threads were merged into the current thread execution. Its execution relationship is as follows:


Figure 4: The process of thread merging

Public final void Join ()
Wait for the thread to terminate

Public final void Join (long Millis);
The maximum time to wait for the thread to terminate is Millis milliseconds. A timeout of 0 means you have to wait all the time.

Public final void Join (long millis, int nanos)
Waits for the thread to terminate for a maximum of Millis milliseconds + Nanos nanoseconds

This common application is the installation program, many large software will contain multiple plug-ins, if you choose a full installation, you have to wait until all plug-ins are installed to finish, and there may be dependencies between the plug-in and plug-ins.

"Demo5": Thread merge

/** * Plugin 1 */class Plugin1 implements Runnable {   @Override public   void Run () {      System.out.println ("plug-in 1 start installation.");      System.out.println ("In-installation ...");      try {         thread.sleep;      } catch (Interruptedexception e) {         e.printstacktrace ();      }      SYSTEM.OUT.PRINTLN ("plug-in 1 Complete installation.");}   } /** * Plugin 2 */class Plugin2 implements Runnable {   @Override public   void Run () {      System.out.println ("plug-in 2 start installation .");      System.out.println ("In-installation ...");      try {         thread.sleep;      } catch (Interruptedexception e) {         e.printstacktrace ();      }      SYSTEM.OUT.PRINTLN ("plug-in 2 Complete installation.");}   }

Calls to merge Threads:

System.out.println ("Main thread open ..."); Thread thread1 = new Thread (new Plugin1 ()); Thread thread2 = new Thread (new Plugin2 ()); try {   thread1.start ();   Start the installation of plug-in 1   thread1.join ();       Wait for the plug-in 1 installation thread to end   Thread2.start ();   Then start the installation of plugin 2   thread2.join ();       Wait until the installation thread of plug-in 2 finishes to return to the main thread} catch (Interruptedexception e) {   e.printstacktrace ();} System.out.println ("Main thread end, program installation complete!") ");

The results are as follows:

Main thread Open ...
Plug-in 1 starts to install.
Installation in ...
Plug-in 1 completes the installation.
Plug-in 2 starts to install.
Installation in ...
Plug-in 2 completes the installation.
The main thread ends, the program installation is complete!

Precedence (priority)

Thread priority refers to the priority program that gets CPU resources. High priority is easy to get CPU resources, the priority bottom of the more difficult to obtain CPU resources, it is shown that the higher the priority to execute more time.

Java gets and sets the priority of the thread through the GetPriority and SetPriority methods. The thread class provides three constants that represent precedence: the min_priority has the lowest priority, the 1;norm_priority is the normal priority, and the highest priority for 5,max_priority is 10. After we create the thread object, the default is 5 if the setting priority is not displayed.

"Demo": Thread priority

/** * Priority */class Prioritythread implements runnable{   @Override public   void Run () {for      (int i = 0; i < 100 0; i + +) {         System.out.println (Thread.CurrentThread (). GetName () + ":" + i);}}   }

Calling code:

Create three threads thread Thread1 = new Thread (new Prioritythread (), "Thread1"); Thread thread2 = new Thread (new Prioritythread (), "Thread2"); Thread thread3 = new Thread (new Prioritythread (), "Thread3");//Set Priority thread1.setpriority (thread.max_priority); Thread2.setpriority (8);//Start Execution thread Thread3.start (); Thread2.start (); Thread1.start ();

From the results we can see that the thread thread1 is significantly faster than the thread thread3 execution.


If you have any doubts and ideas, please give feedback in the comments, your feedback is the best evaluator! Due to my limited skills and skills, if the Ben Boven have errors or shortcomings, please understand and give your valuable advice!

Original: http://blog.csdn.net/luoweifu/article/details/46673975
Author: Luoweifu

"Go" programming ideas multi-threaded and multi-process (3) multithreading in--java

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.