Multithreading Small Example

Source: Internet
Author: User

1. Thread small Example
 /** * Lose a day very easy, want to return to have no way!  * 2016-11-17 1:43:51 * * Process: can contain one or more threads! A thread is really executing on the CPU! * * Multi-Threading Method: * 01. Inherit the thread class rewrite run () * 02. Implement Runnable Interface rewrite run () * Multithreading: In a single program, run multiple threads at the same time to do different work! The technology that multiple threads execute concurrently! * Concurrency: There are several programs in the same time period between the start run and the completion of the run! * The computer runs several programs at the same time, or runs multiple processes or threads of the same program!  * Stand down, ready! Run!   * Athlete's status???                Concurrent!    * Autumn is a high-fat period of colds! * * At a certain point of event!                    Only one thread is executing! * * Run () and start () Difference: * Run (): is a common method in the class, if there are two classes in the run (), then it must be a run () after the execution of the other run (); * Modifier must be public!            The return value type must be void! * Start (): Start thread only if start () is executed! This is a ready state!   Run () is executed by default, and you do not have to wait for the contents of run to complete! * The call to start () does not immediately execute run ()! But in an inexact time! When the CPU allocates time slices to the current thread, the current thread executes the code inside the run ()! * * Thread life cycle: * 1. Freshman * Thread01 thread01=new Thread01 ();         * 2. Ready * Thread01.start (); * 3. Run * CPU allocation time slice to THREAD01, execute run () * 4. Block * sleep ();  Wait () * 5. Death * 001. Normal run () normally exits after execution is completed * 002. Abnormal run () in the course of execution, abnormal conditions, unusual exit! * Thread Priority! * The default value is 5, the minimum value is 1, the maximum value is 10! * Thread01.setpriority (9); */public class MyThread {public static void main (string[] args) {//creation of the first thread inherits the thread Thread01 thread0        1=new Thread01 ();        Thread01.setname ("Current thread--1");        Thread01.start ();        System.out.println ("**************");        Creating a second thread implements the runnable thread Thread02=new thread (new Thread02 ());  Thread02.setpriority (9);        Set Priority Thread02.setname ("Current thread--2");            Thread02.start (); }}//01.     Inherit Thread rewrite run () class THREAD01 extends thread{private int count; Even and public void run () {count<=100} between output 0-100 {if (count%2==0) {//Get current            Executing thread thread.currentthread () System.out.println (Thread.CurrentThread (). GetName () + ":" +count);        } count++; }}}//02. Implement Runnable interface rewrite run () class THREAD02 implements runnable{private int CoUnt Even and public void run () {count<=100} between output 0-100 {if (count%2==0) {//Get current            Executing thread thread.currentthread () System.out.println (Thread.CurrentThread (). GetName () + ":" +count);        } count++; }     }}

2. Synchronous code method for selling tickets
public class Saleticket implements runnable{//Stock count private int tickets=100;  /* * Sell Ticket Synchronization code method is higher than the synchronous code block performance!     But the function is consistent!  * A class can have multiple synchronization methods or synchronous code blocks * * When an object calls the synchronization method in this object!  You can also call other synchronization methods at the same time!     No waiting! * But an object executes the synchronized code block in this object! All the synchronization blocks in this object are locked!     All must wait!     * Synchronous code block lock is an object is not a code block! * */private synchronized void sale () {if (tickets>0) {System.out.println (thread.current            Thread (). GetName () + "sell" +tickets+ "ticket");        Number of votes -1 tickets--;  } try {Thread.Sleep (2);        Let CPU reallocate time slice} catch (Interruptedexception e) {e.printstacktrace ();        }} @Override public void Run () {while (tickets>0) {sale ();        }} public static void Main (string[] args) {saleticket ticket=new saleticket ();        Thread T1=new thread (ticket);        Thread T2=new thread (ticket);        Thread T3=new thread (ticket); Thread t4=new THREAD (ticket);        Set window name t1.setname ("Window 1th");        T2.setname ("Window No. 2nd");        T3.setname ("Window No. 3rd");        T4.setname ("Window No. 4th");        Start selling tickets T1.start ();        T2.start ();        T3.start ();            T4.start (); }  }

3. Synchronizationcode block method implementation selling tickets
public class Saleticket implements runnable{     //Stock count     private  int   tickets=100;        /     * * But  an object executes the synchronized code block in this object! All the synchronization blocks in this object are locked! All must wait!     *      Synchronous code block lock is an object is  not a code block!     *      */
Publicclassimplements runnable{    private int count = 100;//stock votes
   @Override
public void Run () {
While (Count > 0) {
//Sync code block 
    synchronized (this) {
     System.out.println (thread.c Urrentthread (). GetName () + "sold"
       + count + "ticket. ");
     count--;
    }
    try {
     thread.sleep (2);
    } catch (Interruptedexception e) {
     e.printstacktrace ();
    }
  }
 } public static void Main (string[] args) {Saleticket ticket =new Saleticket (); Thread T1=new thread (ticket); Thread T2=new thread (ticket); Thread T3=new thread (ticket); Thread T4=new thread (ticket); Set window name t1.setname ("Window 1th"); T2.setname ("Window No. 2nd"); T3.setname ("Window No. 3rd"); T4.setname ("Window No. 4th"); Start selling tickets T1.start (); T2.start (); T3.start (); T4.start (); } }

4. Small summary /*runnable thread callable future multithreading Runnable and callable Difference 01. Runnable default Specifies the method to execute when run (); Callable default Specifies the method to execute when call (), 02.Runnable Run () has no return value, call () in callable has a return value of 03.run () cannot declare an exception! Must be handled internally! Call () can declare an exception 04. When running callable, you can get a future object! The future is a pattern! Core thought = = = "The time period that originally needs to wait, can now go to do some other business logic!" Suppose that there is now a () with a return value of a () and a B () and C () before we call a () must wait for a () to return the structure before it can call B () or C () now we call a () do not wait for a () to return the structure can also call B () or C

5. Verifying the lock of the synchronization method
public class A implements Runnable {    //This method  other threads can also enter public   synchronized  void  test () {       System.out.println ("Start ...");       try {        thread.sleep;    } catch (Interruptedexception e) {        e.printstacktrace ();    }       System.out.println ("End ...");         @Override public    Void Run () {        test ();    }         public static void Main (string[] args) {for        (int i = 1; I <=5; i++) {            thread thread=new thread (new A ()); 
      thread.start ();}}}              

Verifying the lock on the synchronization method 6. Verifying the lock of the synchronization code block
public class A implements Runnable {    //Verify that the synchronization code library lock is the current object public   void  Test () {            synchronized (this) {                   System.out.println ("Start ...");                   try {                    thread.sleep;                } catch (Interruptedexception e) {                    e.printstacktrace ();                }                   System.out.println ("End ...");}        @Override public    Void Run () {        test ();    }            public static void Main (string[] args) {        a a=new a ();        for (int i = 1; I <=5; i++) {            thread thread=new thread (a);            Thread.Start ();}}}    

Multithreading Small Example

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.