Java concurrent programming 1_ How to implement multi-threading

Source: Internet
Author: User

There are two ways to create threads in Java: Inherit the thread or implement the Runnable interface.

1 inherit the thread class, overriding the Run method:

/** * The first way to implement threading: inheriting thread * Implementing data sharing requires setting properties to static * @author qhyuan1992 * */class MyThread extends thread{private int count;//s Taticpublic MyThread (String ID) {super (ID);} public void Run () {while (Count < 5) {count + +; System.out.println (CurrentThread () + "--->" + count);}}} Class Test{public static void Main (string[] args) {Thread T1 = new MyThread ("Thread_1"); Thread t2 = new MyThread ("Thread_2"); T1.start (); T2.start ();}} Output (not shared Resource)//thread[thread_1,5,main]--->1//thread[thread_2,5,main]--->1//thread[thread_1,5,main]--- >2//thread[thread_1,5,main]--->3//thread[thread_1,5,main]--->4//thread[thread_2,5,main]--->2// Thread[thread_1,5,main]--->5//thread[thread_2,5,main]--->3//thread[thread_2,5,main]--->4//Thread[ Thread_2,5,main]--->5

2 Implement the Runnable interface, override the Run method, and pass it as a parameter to the thread object.

/** * Second way to implement threading: Implement Runnable Interface * Achieve data sharing * @author qhyuan1992 */class myrunnable implements Runnable{private int Count;publ IC void Run () {while (Count < 5) {count + +; System.out.println (Thread.CurrentThread () + "--->" + count);}} public static void Main (string[] args) {myrunnable runnable = new myrunnable (); thread T1 = new Thread (runnable); Thread t2 = new Thread (runnable); T1.start (); T2.start ();}} Output (Use the same Runnable object to construct the Thread object for resource sharing)//thread[thread-0,5,main]--->2//thread[thread-1,5,main]--->2// Thread[thread-1,5,main]--->3//thread[thread-1,5,main]--->4//thread[thread-1,5,main]--->5


What is the difference between the two ways? As you can see from the source code, the thread class implements the Runnable interface.

Publicclass Thread implements Runnable {    ...    /* What'll be run. */    private Runnable target;//target is the Runnable object that we pass when we use the second method */The group of this    thread */private Threadgrou P group;...public Thread (Runnable target) {//second constructor using thread mode    init (null, Target, "thread-" + nextthreadnum (), 0);}}

The local Method Start0 () is called when the start () method of the thread class is called;

Public synchronized void Start () {...        Boolean started = false;        try {            start0 ();            started = true;        } Finally {            ...        }    } Private native void Start0 ();

In summary, you will be called to the Run method:

/**     * If This thread is constructed using a separate     * <code>Runnable</code> run object, then That
   * <code>Runnable</code> object ' s <code>run</code> method is called;     * Otherwise, this method does nothing and returns.     * <p>     * Subclasses of <code>Thread</code> should override this method.     *     * @see     #start ()     * @see     #stop ()     * @see     #Thread (Threadgroup, Runnable, String)     */    @Override public    void Run () {        if (target! = null) {            target.run ();        }}

If you use runnable to construct the thread, the Run method of the Runnable object is called, otherwise, nothing is done. However, by inheriting the thread, the overridden run method is executed because polymorphic does not execute the Run method in the thread class at all.

For example, if inheriting from thread implements the Run method, it also constructs the thread result by runnable which run method is executed? The answer is OK: The Run method that we write in inherits from the thread class is executed.

Class Myrunnable implements Runnable{public void Run () {System.out.println ("myrunnable");}} Class MyThread extends Thread{public MyThread (Runnable R) {super (R);} public void Run () {System.out.println ("MyThread");}} Class Test{public static void Main (string[] args) {Thread t = new MyThread (new Myrunnable ()); T.start ();}} Output://mythread


Do you use thread or runnable?

The benefits of implementing the Runnable interface are more than inheriting the thread class:

1. For multiple threads of the same program code to handle the same resource, inheriting the thread requires that the shared resource be set to static.

2. You can avoid the restriction of single inheritance in Java

3. Increase the robustness of the program, the code can be shared by multiple threads, code and data Independent.

Change the Count field of the first code to static
Class MyThread extends thread{private static int count;//staticpublic MyThread (String ID) {super (ID);} public void Run () {while (Count < 5) {count + +; System.out.println (CurrentThread () + "--->" + count);}}} Class Test{public static void Main (string[] args) {Thread T1 = new MyThread ("Thread_1"); Thread t2 = new MyThread ("Thread_2"); T1.start (); T2.start ();}} Output (Result indeterminate)//thread[thread_1,5,main]--->2//thread[thread_2,5,main]--->2//thread[thread_2,5,main]--- >3//thread[thread_2,5,main]--->4//thread[thread_2,5,main]--->5

You can see how you can share resources using static, as well as implementing multithreading in the second way, provided that the Runnable object that creates the thread is the same.


Be careful to see that the printed structure is not what we expected, for example:

Thread[thread_1,5,main]--->2

Thread[thread_2,5,main]--->2

The result of this is that multithreading concurrency is not controllable, and the issue of thread synchronization continues to be explored later.

Java concurrent programming 1_ How to implement multi-threading

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.