Java-thread and runnable Implement multithreading

Source: Internet
Author: User
Tags ticket

Java Multithreading Series--the "basic article" 02 of the common implementation of multithreading two ways

Overview

In this chapter, we learn the "2 common ways to implement multithreading":thread and Runnable.
This is commonly used because multithreading can also be achieved through the thread pool in the Java.util.concurrent package. We'll go into details about the thread pool, and now we'll get to the thread and runnable. The contents of this chapter include:
Introduction to Thread and runnable
The similarities and differences between thread and runnable
Multithreading examples of thread and runnable

Reprint Please specify source:http://www.cnblogs.com/skywang12345/p/3479063.html

Introduction to Thread and Runnable

Runnable is an interface that contains only a run () method. It is defined as follows:

Public interface Runnable {public    abstract void run ();

runnable function, realize multithreading. We can define a class A to implement the Runnable interface, and then create a new thread by means of the new thread (new A ()).

Thread is a class. Thread itself implements the Runnable interface. It declares the following:

public class Thread implements Runnable {}

Thread's role in implementing multithreading.

the similarities and differences between thread and runnable

the same point of thread and Runnable : "Multithreading is the way to implement."
different points of Thread and Runnable :
Thread is a class, and runnable is an interface; the thread itself is the class that implements the Runnable interface. We know that "a class can have only one parent class, but it can implement multiple interfaces," So runnable has better extensibility.
In addition, runnable can also be used for "resource sharing". That is, multiple threads are built on a Runnable object that shares the resources on the Runnable object.
In general, it is recommended to implement multithreading through "Runnable"!

Threading Example 1 for thread and runnable. multithreaded example of thread

The following example is a better understanding of thread and runnable, using an example on the Internet to compare persuasive examples.

1//Threadtest.java Source 2 class MyThread extends thread{   3     private int ticket=10;   4 public     void Run () {5 for         (int i=0;i<20;i++) {  6             if (this.ticket>0) {7                 System.out.println ( This.getname () + "Sell ticket: Ticket" +this.ticket--); 8             } 9         }10     }};12 public class ThreadTest {+ public     static void Main (string[] args) {  1 5         //start 3 thread t1,t2,t3; sell 10 tickets per thread!         MyThread t1=new MyThread ();         MyThread t2=new MyThread ();         MyThread t3=new MyThread ()         ; T1.start ();         T2.start ();         T3.start ();       

Operation result :

Thread-0 Sell ticket: Ticket10thread-1 Sell ticket: Ticket10thread-2 Sell ticket: Ticket10thread-1 Sell ticket: ticket9thread-0 Sell ticket: ticket9thread-1 Sell ticket: Ticket8thread-2 Sell ticket: Ticket9thread-1 Sell ticket: ticket7thread-0 Sell ticket: Ticket8thread-1 Sell ticket: Ticket6thread-2 Sell ticket: ticket8Thread-1 Sell ticket: ticket5thread-0 Sell ticket: Ticket7thread-1 Sell ticket: Ticket4thread-2 Sell ticket: Ticket7thread-1 Sell ticket: ticket3thread-0 Sell ticket: ticket6Thread-1 Sell ticket: Ticket2thread-2 Sell ticket: Ticket6thread-2 Sell ticket: Ticket5thread-2 Sell ticket: Ticket4thread-1 Sell ticket: ticket1thread-0 Sell ticket: ticket5Thread-2 Sell ticket: ticket3thread-0 Sell ticket: Ticket4thread-2 Sell ticket: ticket2thread-0 Sell ticket: Ticket3thread-2 Sell ticket: ticket1thread-0 Sell ticket: ticket2Thread-0 Sell Tickets: Ticket1

Result Description :
Mythread inherits from Thread, which is a custom thread. Each mythread will sell 10 tickets.
(02) Main thread main thread create and start 3 mythread child threads. Each sub-thread has sold 10 tickets each.

2. Multithreaded examples of runnable

Below, we make changes to the above program. Implement an interface through Runnable, which enables multithreading.

1//Runnabletest.java Source 2 class MyThread implements runnable{   3     private int ticket=10;   4 public     void Run () {5 for         (int i=0;i<20;i++) {  6             if (this.ticket>0) {7                 System.out.println ( Thread.CurrentThread (). GetName () + "Sell ticket: Ticket" +this.ticket--); 8             } 9         }10     } 11}; public class Runnabletest {+ public     static void Main (string[] args) {         MyThread mt=new mythr EAD ();         //Start 3 thread t1,t2,t3 (they share a runnable object), these 3 threads sell 10 tickets altogether! Thread T1=new Thread (MT), thread         t2=new Thread (MT),         thread t3=new thread (MT),         T1.start ( );         T2.start ();         T3.start ();  25}

Operation result :

Thread-0 Sell ticket: Ticket10thread-2 Sell ticket: Ticket8thread-1 Sell ticket: Ticket9thread-2 Sell ticket: ticket6thread-0 Sell ticket: ticket7thread-2 Sell ticket: Ticket4thread-1 Sell ticket: Ticket5thread-2 Sell ticket: ticket2thread-0 Sell ticket: Ticket3thread-1 Sell ticket: Ticket1

Result Description :
(01) different from the above "mythread inherit from thread"; Here the Mythread implements the thread interface.
(02) The main thread, main, creates and starts 3 sub-threads, and the 3 sub-threads are created based on the Mt Runnable object. The result is that the 3 sub-threads sold a total of 10 tickets. This means that they are sharing the Mythread interface.

description of the difference between start () and run ()

start () : Its role is to start a new thread, and the new thread executes the corresponding run () method. Start () cannot be called repeatedly.
run () : Run () is the same as the normal member method and can be called repeatedly. Calling run () alone will execute run () in the current thread and will not start a new thread!

The following is illustrated in code.

Class MyThread extends thread{public      void Run () {        ...    }}; MyThread MyThread = new MyThread ();

Mythread.start () starts a new thread and runs the Run () method in a new thread.
Mythread.run () runs the Run () method directly in the current thread and does not start a new thread running run ().

example of the difference between start () and run ()

Below, a simple example shows the difference between them. The source code is as follows:

1//Demo.java Source 2 class MyThread extends thread{   3 public     MyThread (String name) {4         super (name); 5     } 6< C6/>7 public     Void Run () {8         System.out.println (Thread.CurrentThread (). GetName () + ' is running '); 9     } 10}; 11 public class Demo {$  public     static void Main (string[] args) {a         Thread mythread=new mythread ("M Ythread ");         System.out.println (Thread.CurrentThread () getName () +" Call Mythread.run () ");         Mythread.run ();         System.out.println (Thread.CurrentThread () getName () + "Call Mythread.start ()");         Mythread.start ();  22}

Operation result :

Main call Mythread.run () main was Runningmain call Mythread.start () Mythread is running

Result Description :
Thread.CurrentThread (). GetName () is the name used to get the "current thread". The current thread is the thread that is dispatching execution in the CPU.
Mythread.run () is called in the main thread main, and the Run () method runs directly on the main thread main.
Mythread.start () will start "Thread Mythread", and "thread Mythread" will invoke the run () method after it is started, and the Run () method at this time is run on thread mythread.

start () and run () related source code (based on jdk1.7.0_40)

The source code for the start () method in Thread.java is as follows:

Public synchronized void Start () {    //If the thread is not "ready", an exception is thrown!)    if (threadstatus! = 0)        throw new Illegalthreadstateexception ();    Add a thread to the Threadgroup    Group.add (this);    Boolean started = false;    try {        //start thread start0 () through start0 ()        ;        Set started tag        started = true;    } finally {        try {            if (!started) {                group.threadstartfailed (this );            }        } catch (Throwable ignore) {        }}}    

description : Start () actually starts the thread through the local method Start0 (). Start0 () will run a new thread, and the new thread will call the run () method.

Private native void Start0 ();

The code for Run () in Thread.java is as follows:

public void Run () {    if (target! = null) {        target.run ();    }}

Description : Target is a runnable object. Run () is the run () method that calls the runnable member of the thread thread directly, and does not create a new thread.

Java-thread and runnable implement multithreading

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.