Java --- 11 --- two ways to create multithreading, java --- 11 --- Multithreading

Source: Internet
Author: User

Java --- 11 --- two ways to create multithreading, java --- 11 --- Multithreading

You can create multiple threads in two ways:

The following are the items in the API documentation:



Public class Thread

Extends Object

Implements Runnable

A thread is an execution thread in a program. Java Virtual Machine allows applications to run multiple execution threads concurrently.

Each thread has a priority. The execution of a high-priority thread takes precedence over that of a low-priority thread. Each thread can or cannot be marked as a daemon. When the code running in a Thread creates a new Thread object, the initial priority of the new Thread is set to the priority of the Creation Thread, and only when the creation Thread is a daemon Thread, the new thread is the daemon.

When a Java Virtual Machine is started, there is usually a single non-daemon thread (it usually calls the main method of a specified class ). Java virtual opportunity continues to execute the thread until any of the following situations occur:

· The exit method of the Runtime class is called, and the security manager can exit the operation.

· All threads of non-daemon threads have stopped running, whether returned from a call to the run method or thrown an exception beyond the run method.

There are two ways to create a new execution thread. One way is to declare the class as a subclass of Thread. This subclass should override the run method of the Thread class. Next, you can allocate and start instances of this subclass. For example, a thread that calculates the prime number greater than a specified value can be written as follows:


class PrimeThread extends Thread{    long minPrime;    PrimeThread(long minPrime)    {        this.minPrime = minPrime;    }    public void run()    {        // compute primes larger than minPrime        . . .    }}


 

Then, the following code creates and starts a thread:

PrimeThread p = new PrimeThread(143);p.start();

Another way to create a thread is to declare a class that implements the Runnable interface. This class then implements the run method. Then, you can allocate instances of this class and pass and start them as a parameter when creating a Thread. The same example using this style is as follows:

 

class PrimeRun implements Runnable{    long minPrime;    PrimeRun(long minPrime)    {        this.minPrime = minPrime;    }    public void run()    {        // compute primes larger than minPrime        . . .    }}


 

Then, the following code creates and starts a thread:

PrimeRun p = new PrimeRun(143);new Thread(p).start();

Each thread has a Identification name, and multiple threads can have the same name. If no identification name is specified during thread creation, a new name is generated.

---------------------------------------------

Thread creation method:

1. inherit from Thread

2. Implement Runnable

 

Method 1: Inherit the Thread class

Steps:

1. Custom classes inherit from Thread

2. Review the run () method in Thread

3. Create an object of this class, call the start () method, enable the thread, and call the run method.

 

Simple implementation:


class MyThread extends Thread{    public void run ()    {        for (int i = 0; i < 100; i++)        {            System.out.println("MyThread.run()..."+i);        }    }}public class THREAD{    public static void main (String[] args)    {        MyThread a = new MyThread();        a.start();        for (int j = 0; j < 100; j++)        {            System.out.println("THREAD.main()----"+j);        }    }}


When running multiple times, you will find that:

The thread where I is located and the thread where j is located run alternately.

However, the results of each operation are different.

This is the randomness of multithreading.

 

Why overwrite the run method?

Thread is used to describe the Thread. This class defines a function used to store the code to be run by the Thread.

This storage function is the run method.

 

Method 2: Runnable

Runnable is a simple interface with only one abstract method: run method.

Steps:

1. Define a class to implement the Runnable interface

2. overwrite the run Method

3. Create this class object, and create a Thread Class Object with this class object as the parameter, thus creating a Thread

4. Call the start method, enable the thread, and call the run method.

 

Simple creation:


class MyThread implements Runnable{    public void run ()    {        for (int i = 0; i < 50; i++)        {            System.out.println("MyThread.run()..."+i);        }    }}public class THREAD{    public static void main (String[] args)    {        MyThread a = new MyThread();        Thread a1 = new Thread(a);        Thread a2 = new Thread(a);        Thread a3 = new Thread(a);        Thread a4 = new Thread(a);        a1.start();        a2.start();        a3.start();        a4.start();    }}


In this example, four threads are created to achieve the alternate operation of the four threads, but it cannot be seen which thread is executed,

The getName method in the Thread class can solve this problem.


System.out.println(Thread.currentThread().getName()+"..."+i);

CurrentThread (): Get the current thread object

Thread name

Thread-0

Thread-1

...

The Thread has its own default name. The Thread-number starts from 0.

You can also define the thread name.


class MyThread implements Runnable{    private String name;    public MyThread(String name)    {        this.name = name;    }    public String GetName()    {        return name;    }    public void run ()    {        for (int i = 0; i < 50; i++)        {            System.out.println(this.GetName()+"..."+i);        }    }}public class THREAD{    public static void main (String[] args)    {        MyThread a = new MyThread("My");        MyThread b = new MyThread("Your");        Thread a1 = new Thread(a);        Thread a2 = new Thread(b);        a1.start();        a2.start();    }}


If super is used directly to inherit the Thread class,

Because the Thread class has the getName method, you can initialize the Thread through the constructor and then directly call the getName method.


class MyThread extends Thread{    private String name;    public MyThread(String name)    {        super(name);    }//public String GetName(){//return name;//}    public void run ()    {        for (int i = 0; i < 50; i++)        {            System.out.println(Thread.currentThread().getName()+"..."+i);        }    }}public class THREAD{    public static void main (String[] args)    {        MyThread a = new MyThread("My");        MyThread b = new MyThread("Your");//Thread a1 = new Thread(a);//Thread a2 = new Thread(b);        a.start();        b.start();    }}



Differences between the two methods:

Method 1: Inherit the Thread:

1. disadvantage: the Java language only allows single inheritance. Therefore, this class cannot inherit other classes after it inherits the Thread.

2. Advantages: easy to write.

Method 2: implement the Runnable interface:

1. Disadvantages: relatively complex writing

2. Advantages:

A) Avoid the limitations caused by single inheritance

B) It is conducive to code robustness. The code can be shared by multiple threads, and the code and data are independent.

Code storage location:

Inherited Thread method: the Thread code is stored in the run method of the Thread subclass.

Runnable mode: the thread code is stored in the run method of the interface subclass.



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.