Java Multithreaded Understanding

Source: Internet
Author: User

the two ways that Java implements multithreading are to inherit the thread class and implement the Runnable interface, respectively.

code example:

Class MyThread extends thread{private String name;  Public MyThread (String name) {  this.name = name;}  @Override public   Void, run () {for  (int i=0;i<7;i++) {   System.out.println ("Thread Start:" +this.name+ "number" +i);  }}}
Class Myrun implements runnable{@Override public void Run () {for  (int i=0;i<7;i++) {   System.out.println (" Thread Start: "+thread.currentthread (). GetName () +" number of times "+i);  }}
public class a{public static void Main (String [] args) {   MyThread MyThread = new MyThread ("MyThread");  Mythread.start ();   Myrun Myrun = new Myrun ();  Thread run1 = new Thread (Myrun, "Myrun");  Run1.start (); }}
Operation Result:


key point 1: The start thread uses the start () method, and the run () method does not start a new thread.
public class a{public static void Main (String [] args) {   MyThread myThread1 = new MyThread ();  Mythread1.run ();   MyThread myThread2 = new MyThread ();  
Class MyThread extends thread{public void run () {for  (int i=0;i<7;i++) {   System.out.println ("Thread:" + Thread.CurrentThread (). GetName () + "number of times" +i);  }}

Start () : Starts a new thread by calling start0 () , and the new thread executes the corresponding run () method. Start () cannot be called repeatedly.

run (): Run () can be called repeatedly as a normal member method. A separate call to run () executes run () in the current thread and does not start a new thread!


Related Source:

Public synchronized void Start () {if (Threadstatus! = 0) The//start () method cannot be called repeatedly, otherwise throws an exception throw new Illegalt        Hreadstateexception (); /* Notify The group, the this thread was about to being started * so that it can be added to the group's list of Threa DS * and the group ' s unstarted count can be decremented.  */Group.add (this);        Added to the thread group, Boolean started = false;            try {start0 ();        started = true;                } finally {try {if (!started) {group.threadstartfailed (this); }} catch (Throwable ignore) {/* do nothing. If Start0 threw a throwable then it'll be passed up the call stack */}}}}privat e native void Start0 (); @Overridepublic void Run () {if (target! = null) {//target is the current Runnable object Targ        Et.run (); }    }

key point 2:thread implements multi-threading and Runnable Implementation of multithreading differences. 1, because Java uses single inheritance, multi- interface implementation principle, so through the runnable interface to achieve multithreading more flexibility; 2.runnable objects can be shared by multiple threads and are suitable for situations where multiple threads are working on the same resource. (not accurate)

Question of selling tickets:

1:thread

Class MyThread extends thread{private int tickets =5;   @Override public      Void Run () {    while (tickets>0) {              tickets--;            System.out.println (Thread.CurrentThread (). GetName () + "sold one ticket, remaining votes:" +tickets);}}    
public static void Main (String [] args) {   MyThread myThread1 = new MyThread ();  Mythread1.start ();   MyThread myThread2 = new MyThread ();  Mythread2.start (); }

MyThread myThread1 = new MyThread (); MyThread myThread2 = new MyThread (); because the new Mythread object was created each time , the final result was to sell 10 tickets;
2:Runnable
Class MyThread extends thread{private int tickets =5;   @Override public      Void Run () {    while (tickets>0) {              tickets--;            System.out.println (Thread.CurrentThread (). GetName () + "sold one ticket, remaining votes:" +tickets);}}    
public static void Main (String [] args) {   myrunnable r = new Myrunnable ();                   thread T1 = new Thread (r);       Thread t2 = new Thread (r);              T1.start ();     T2.start ();   }

Myrunnable objects have only one, multi-threaded sharing the same object, so the result seems to be the correct ticket.


key point 3: Share resources by implementing the Runnable interface.
Class Myrunnable implements runnable{    private int tickets =10;      @Override public      Void Run () {       while (tickets>0) {               try {                  thread.sleep ()               } catch ( Interruptedexception e) {                   e.printstacktrace ();               }               tickets--;             System.out.println (Thread.CurrentThread (). GetName () + "sold one ticket, remaining votes:" +tickets);}             

apparently the last remaining votes-1 and-2 are not correct, so The only implementation of the Runnable interface is unable to share the resources, if you need to share or to join the Synchronized keyword.

Class Myrunnable implements runnable{    private int tickets =10;      @Override public      Void Run () {       synchronized (the) {      while (tickets>0) {                  tickets--;                System.out.println (Thread.CurrentThread (). GetName () + "sold one ticket, remaining votes:" +tickets);}}}      

Java Multithreaded Understanding

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.