Getting Started with java-multithreading (i)

Source: Internet
Author: User
Tags ticket

Getting Started with java-multithreading (i) The difference between a process and a thread

A process is the process of a dynamic execution of a program, which needs to undergo a complete process of loading from code, execution of code, and completion of execution, which is the process of process re-production and development to final Extinction. The Multi-process operating system utilizes the Cpu's time-sharing mechanism to execute different programs in separate periods, because the CPU runs very fast, so it wants to be run simultaneously by multiple Processes.

A thread is a smaller execution unit than a process, and threads are further divided on the basis of the PROCESS. Multithreading refers to a process that can produce multiple smaller program units during execution, and these smaller units become threads that can exist simultaneously while running.

The so-called thread is the process of running a program, multithreading means that you can run multiple blocks at the same time (the Java language supports multithreading).

Implementation of Threads

There are two main ways, the first is to inherit the thread class, the second is to implement the Runable Interface.

Inherit the thread class

The thread class is defined in the Java.lang package, and a class is called a multithreaded implementation class as long as it inherits the thread class. In the thread subclass, you must override the run () method, which is the Thread's principal, and the thread class is defined as Follows:

1  packageSep18;2 /*3 * Format of thread class4 * Class Name extends thread{5 * attribute------;6 * method------;7 * public void run () {8 * Thread body;9  *     }Ten  * } one  */ a  public classThreadDemo01 { -      public Static voidmain (String Args[]) { -MyThread mt1=NewMyThread ("thread a"); theMyThread mt2=NewMyThread ("thread b"); -          -Mt1.start ();//Start Multithreading -Mt2.start ();//Start Multithreading +          -     } + } a classMyThreadextendsthread{ at     PrivateString name; -      publicMyThread (String Name) { -          this. name=name; -     } -      public voidRun () { -          for(inti=0;i<10;i++){ inSystem.out.println (name+ "run, i=" +i); -         } to     } +}
Thread A runs, i=0 thread Aruns, i =1 threada runs, i =2 threada runs, i =3 thread aruns, i =4 thread Bruns, i =0 thread B runs, I =1 Thread A runs, i=5 thread Aruns, i =6 thread aruns, i =7 thread a runs, i=8 thread B runs, i=2 thread a runs, I=9 thread Bruns, i =3 threadb runs, i =4 thread b runs, i=5 thread Bruns, i =6 thread Bruns, i =7 thread B runs, i=8 thread B runs, I=9

If a class implements multiple threads by inheriting the thread method, then only one call to the start () method is allowed, and no exception occurs.

Implementing the Runnable Interface

The Runnable interface only defines an abstract method: public void run ();

/* 3  * Format of thread Class 4  * Class name implements THREAD{5  *         attribute------; 6  *         method------; 7 * Public         V OID Run () {8  *             thread body; 9  *     }10  *}11  **
1  packageSep18; a  public classThreadDemo02 { -      public Static voidmain (String Args[]) { -MyThread2 mt1=NewMyThread2 ("thread a"); theMyThread2 mt2=NewMyThread2 ("thread b"); -Thread t1=NewThread (mt1); -Thread t2=NewThread (mt2); -T1.start ();//Start Multithreading +T2.start ();//Start Multithreading -          +     } a } at classMyThread2Implementsrunnable{ -     PrivateString name; -      publicMyThread2 (String Name) { -          this. name=name; -     } -      public voidRun () { in          for(inti=0;i<10;i++){ -System.out.println (name+ "run, i=" +i); to         } +     } -}
 thread A runs, i=0 thread A runs, i  =1 thread b runs, I  =0< Span style= "color: #000000;" > thread A runs, i  =2 thread b runs, i  =1 thread A runs, i  =3< Span style= "color: #000000;" > thread b runs, i  =2 thread A runs, i  =4 thread b runs, I  =3< Span style= "color: #000000;" > thread A runs, i  =5 thread b runs, i  =4 thread A runs, i  =6< Span style= "color: #000000;" > thread b runs, i  =5 thread A runs, i  =7 thread b runs, I  =6< Span style= "color: #000000;" > thread A runs, i  =8 thread b runs, i  =7 thread A runs, i  =9< Span style= "color: #000000;" > thread b runs, i  =8 thread b runs, I  =9 

After actually implementing the Runnable interface, the starting thread is still using the two constructor of thread: public thread (Runnable target), and public thread (Runnable target, String name); Both of these constructors accept the subclass instance object of the runnable interface.

Using runnable interface to realize the advantage of multithreading

First 1th: Avoid the limitations imposed by Java single inheritance.

Then: to enhance the robustness of the program, the code can be shared with a thread, the code and data are Independent. For situations where multiple identical program code handles the same resource.

See the following example to understand the 2nd:

Use the Inherit thread class:

1  packageSep18;2 3  public classThreadDemo03 {4      public Static voidmain (String Args[]) {5MYTHREAD02 mt01=NewMyThread02 ();6MYTHREAD02 mt02=NewMyThread02 ();7MYTHREAD02 mt03=NewMyThread02 ();8 Mt01.start ();9 Mt02.start ();Ten Mt03.start (); one     } a } - classMyThread02extendsthread{ -     Private intTicket=5; the      public voidRun () { -          for(inti=0;i<=12;i++){ -             if(ticket>0){ -System.out.println ("sell one ticket, rest:" +ticket+ "zhang"); +ticket--; -             } +         } a     } at}
Sell one ticket, remaining: 5 sell one ticket, remaining: 4 one ticket, remaining: 5 tickets sold, remaining: 5 for one ticket, remaining: 4 for one ticket, remaining: 3 for one ticket, remaining: 2 for one ticket, remaining: 1 for one ticket, remaining: 3 for one ticket, the Remaining: 2 for one ticket, Remaining: 4 Tickets sold, remaining: 1 sold one ticket, remaining: 3 tickets sold, remaining: 2 tickets sold, remaining: 1

Multithreading for data sharing using the runnable interface. ( the core is that such a subclass can use multiple start ())

1  packageSep18;2 3  public classThreadDemo04 {4      public Static voidmain (String Args[]) {5MYTHREAD03 mt01=NewMyThread03 ();6     NewThread (mt01). start ();7     NewThread (mt01). start ();8     NewThread (mt01). start ();9     Ten     } one } a classMyThread03Implementsrunnable{ -     Private intticket=10; -      public voidRun () { the          for(inti=0;i<=12;i++){ -             if(ticket>0){ -System.out.println ("sell one ticket, surplus:" +ticket--); -             } +         } -     } +}

Getting Started with java-multithreading (i)

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.