Three ways and differences in Java implementation threads

Source: Internet
Author: User

Three ways and differences in Java implementation threads

Java three ways to implement threads:

    1. Inherit thread
    2. Implementing the Runnable Interface
    3. Implementing the Callable Interface

Difference:

    1. The first way to inherit the thread can not inherit other classes, the following two kinds of possible;
    2. Use the latter two ways to share a target with multiple threads;
    3. Callable a return value more than runnable, and the call () method can throw an exception;
    4. Access the thread name, the first direct use of This.getname (), and the latter two using Thread.CurrentThread (). GetName ().

Let's look at the implementation and the difference by code:

Three types of implementations:

//1. Inheriting the thread, overriding the run () methodclassThread1extendsThread {Private intn =5;@Override     Public void Run() { while(N >0) {System. out.println("Name:"+ This.GetName() +", N:"+ N);        n--; }    }}//2. Implementing the Runnable interface, implementing the Run () methodclassThread2ImplementsRunnable {Private intn =5;@Override     Public void Run() { while(N >0) {System. out.println("Name:"+ Thread.CurrentThread().GetName() +", N:"+ N);        n--; }    }}//3. Implementing the callable interface, implementing the call () method with return values and exceptionsclassThread3Implementscallable<string> {Private intn =5;@Override     PublicStringPager()throwsException { while(N >0) {System. out.println("Name:"+ Thread.CurrentThread().GetName() +", N:"+ N);        n--; }returnString.valueOf(n); }    }

How to use:

//First way of realizationThread1 T11 =New Thread1(); Thread1 T12 =New Thread1(); Thread1 t13 =New Thread1(); T11.Start(); T12.Start(); t13.Start();//Second realization modeThread2 t21 =New Thread2(); Thread2 t22 =New Thread2(); Thread2 t23 =New Thread2(); Thread t211 =NewThread (t21); Thread t212 =NewThread (t22); Thread t213 =NewThread (t23); t211.Start(); t212.Start(); t213.Start();//Third implementationThread3 t31 =New Thread3(); Thread3 T32 =New Thread3(); Thread3 T33 =New Thread3(); Futuretask<string> F1 =NewFuturetask<> (T31); futuretask<string> F2 =NewFuturetask<> (T32); Futuretask<string> F3 =NewFuturetask<> (T33); Thread t311 =NewThread (F1); Thread t312 =NewThread (F2); Thread t313 =NewThread (F3); t311.Start(); t312.Start(); t313.Start();

From the code can be seen above mentioned difference 1,3,4. So what does the difference 2 mean by sharing a target?

First, let's look at the results of the above code,

The first type:

Name:thread-1N:5Name:thread-1N:4Name:thread-1N:3Name:thread-1N:2Name:thread-1N:1Name:thread-2N:5Name:thread-2N:4Name:thread-2N:3Name:thread-2N:2Name:thread-2N:1Name:thread-0N:5Name:thread-0N:4Name:thread-0N:3Name:thread-0N:2Name:thread-0N:1

The second type:

Name:thread-4N:5Name:thread-4N:4Name:thread-4N:3Name:thread-3N:5Name:thread-5N:5Name:thread-3N:4Name:thread-4N:2Name:thread-4N:1Name:thread-3N:3Name:thread-3N:2Name:thread-3N:1Name:thread-5N:4Name:thread-5N:3Name:thread-5N:2Name:thread-5N:1

As you can see, the result of both approaches is new three threads, which loop 5 times inside each thread. D The second approach does not reflect the sharing of the same target. If we change the way the second thread is created:

//第二种实现方式newThread2newThread2newThread2newnewnew Thread(t21);t211.start();t212.start();t213.start();

Look at the results of the operation:

name:Thread-4, n:5name:Thread-4, n:4name:Thread-4, n:3name:Thread-4, n:2name:Thread-4, n:1name:Thread-3, n:5name:Thread-5, n:5

As you can see, 3 threads have been started, but since the value of sharing one target,n has changed, the other two threads will know, so they have been looped 5 times in total. But here is clearly 7 times Ah, this is due to multi-threaded synchronization problem, you can add the Synchronized keyword to solve the Run method:

@Overridepublicsynchronizedvoidrun() {  while0) {    System.out.println("name:" + Thread.currentThread().getName", n:" + n);    n--;  }}

Operation Result:

name:Thread-3, n:5name:Thread-3, n:4name:Thread-3, n:3name:Thread-3, n:2name:Thread-3, n:1

This may be a bit confusing, just starting a thread. In fact, the other two threads also started, but this time n=0 can not enter the loop. We can add a line to print:

@Overridepublicsynchronizedvoidrun() {  System.out.println("进入" + Thread.currentThread().getName"线程");  while0) {    System.out.println("name:" + Thread.currentThread().getName", n:" + n);    n--;  }}

You can see the results of the operation:

进入Thread-3线程name:Thread-3, n:5name:Thread-3, n:4name:Thread-3, n:3name:Thread-3, n:2name:Thread-3, n:1进入Thread-5线程进入Thread-4线程

Three ways and differences in Java implementation threads

Related Article

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.