Java------two ways to create multithreading

Source: Internet
Author: User

Two ways to create multithreading:

The following items are in the API documentation:



public class Thread

Extends Object

Implements Runnable

A thread is a thread of execution in a program. A Java virtual machine allows an application to run multiple execution threads concurrently.

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

When a Java virtual machine is started, it usually has a single non-daemon thread (which typically invokes the main method of a specified class). Java virtual opportunities continue to execute threads until any of the following conditions occur:

· The exit method for the Runtime class is called, and the security Manager allows the exit operation to occur.

· All threads that are not daemon threads have stopped running, either by returning from a call to the Run method or by throwing an exception that is propagated beyond the Run method.

There are two ways to create a new thread of execution. One way is to declare a class as a subclass of Thread. The subclass should override the Run method of the Thread class. You can then assign and start an instance of the subclass. For example, a thread that calculates a prime number larger than a specified value can be written as:


Class Primethread extends thread{    long minprime;    Primethread (long Minprime)    {        this.minprime = minprime;    }    public void Run ()    {        //compute primes larger than minprime        ...    }}


The following code then 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. The class then implements the Run method. You can then assign an instance of the class that is passed and started as a parameter when the Thread is created. The same example of 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        ...    }}


The following code then creates and starts a thread:

Primerun p = new Primerun (143); new Thread (P). Start ();

Each thread has an identity name, and multiple threads can have the same name. If the thread is created without specifying an identity name, a new name is generated for it.

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

How threads are created:

1. Inherit thread

2. Implement Runnable

The first way: Inherit the thread class

Implementation steps:

1. Custom class Inheritance Thread

2. Review the Run () method in thread

3. Create an object of the class, call the Start () method, open the thread and call the Run method

Simple implementation:


Class MyThread extends thread{public    void Run ()    {for        (int i = 0; i <; i++)        {            System.out.prin TLN ("Mythread.run () ..." +i);}}    public class thread{public    static void Main (string[] args)    {        MyThread a = new MyThread ();        A.start ();        for (int j = 0; J <; J + +)        {            System.out.println ("Thread.main ()----" +j)        ;    }}


Running multiple times will find:

The thread where I resides and the thread where J is running will run alternately

But the results of each run are different.

That's the randomness of multithreading.

Why overwrite the Run method?

Thread is used to describe threads, and the class defines a feature that stores the code that the thread wants to run

This storage function is the Run method.

Second way to create: implement Runnable

Runnable is a simple interface in which there is only one abstract method: the Run method.

Implementation steps:

1. Define a class that implements the Runnable interface

2. Override the Run method

3. Create the Class object and create an object of the thread class with the class object as a parameter, creating a thread

4. Call the Start method, open the thread and call the Run method.

Simple creation:


Class MyThread implements runnable{public    void Run ()    {for        (int i = 0; i <; 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 were created to enable alternating runs of four threads, but it was not possible to see which thread was executing,

Calling the GetName method in the thread class solves this problem


System.out.println (Thread.CurrentThread (). GetName () + "..." +i);

CurrentThread (): Gets the current thread object

The name of the thread

Thread-0

Thread-1

...

Threads have their own default names, thread-numbering starts from 0

You can also define the name of the thread yourself.


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 <; 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 you are using a method that inherits the thread class directly with Super,

Because there is getname in the thread class, the thread is initialized through the constructor, and then the GetName method is called directly on the line.


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 <; i++)        {            Sys Tem.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 ();    }}



The difference between the two ways:

The first: The method that inherits the thread:

1. Cons: The Java language allows only single inheritance, so the class inherits the thread and can no longer inherit other classes.

2. Advantages: Easy to write.

The second type: the way to implement the Runnable interface:

1. Cons: Write slightly more complex

2. Advantages:

A) Avoid limitations due to single inheritance

b) facilitates the robustness of code, the code can be shared by multiple threads, the code and data are independent

Where the code is stored:

Inherit the thread method: the threading code is stored in the Run method of the thread subclass

Implement runnable mode: Thread code is stored in the Run method of the interface subclass.



Java------two ways to create multithreading

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.