Java multithreading (2) Implementation of threads, java Multithreading

Source: Internet
Author: User

Java multithreading (2) Implementation of threads, java Multithreading
Java multi-thread (2) Implementation of threads

In Java, the run method is used to specify the task to be completed for the thread. There are two technologies to provide the run method for the thread:

  1. inherit the Thread class and override its run method.Then create the subclass object and call the start () method.

  2. Implement the run method by defining classes that implement the Runnable interface.The object of this class is passed in as a parameter when the Thread is created, and then the start () method is called.

 

  Thread classIs a class specifically used to create threads and operate on threads. After a class inherits the Thread class, the class is calledThread.

Both methods must runStart ()Method to allocate required system resources, scheduling threads, and execution threads to the threadRun ()Method.

The start () method is the only way to start a thread. The start () method first prepares system resources for thread execution, and then calls the run () method. A thread can only be started once. It is invalid to start it again.

The run () method puts the thread work into it, that is, everything we want this thread to do. By default, the run () method does nothing.

In a specific application, the method used to construct the thread depends on the situation. Generally, when a thread has inherited another class, it should be constructed using the second method to implement the Runnable interface.

The following two examples are provided to illustrate the two implementation methods of the thread. Each example has two threads:

public class ThreadTest1{    public static void main(String[] args)    {        Thread1 thread1 = new Thread1();        Thread2 thread2 = new Thread2();        thread1.start();        thread2.start();    }}class Thread1 extends Thread{    @Override    public void run()    {        for (int i = 0; i < 100; ++i)        {            System.out.println("Hello World: " + i);        }    }}class Thread2 extends Thread{    @Override    public void run()    {        for (int i = 0; i < 100; ++i)        {            System.out.println("Welcome: " + i);        }    }}
public class ThreadTest1{    public static void main(String[] args)    {        Thread1 thread1 = new Thread1();        Thread2 thread2 = new Thread2();        thread1.start();        thread2.start();    }}class Thread1 extends Thread{    @Override    public void run()    {        for (int i = 0; i < 100; ++i)        {            System.out.println("Hello World: " + i);        }    }}class Thread2 extends Thread{    @Override    public void run()    {        for (int i = 0; i < 100; ++i)        {            System.out.println("Welcome: " + i);        }    }}

 

Public class ThreadTest2 {public static void main (String [] args) {// another implementation method of the thread, you can also use the anonymous internal class Thread thread1 = new Thread (new MyThread1 (); thread1.start (); Thread thread2 = new Thread (new MyThread2 ()); thread2.start () ;}} class MyThread1 implements Runnable {@ Override public void run () {for (int I = 0; I <100; ++ I) {System. out. println ("Hello:" + I) ;}} class MyThread2 implements Runnable {@ Override public void run () {for (int I = 0; I <100; ++ I) {System. out. println ("Welcome:" + I );}}}
Public class ThreadTest2 {public static void main (String [] args) {// another implementation method of the thread, you can also use the anonymous internal class Thread thread1 = new Thread (new MyThread1 (); thread1.start (); Thread thread2 = new Thread (new MyThread2 ()); thread2.start () ;}} class MyThread1 implements Runnable {@ Override public void run () {for (int I = 0; I <100; ++ I) {System. out. println ("Hello:" + I) ;}} class MyThread2 implements Runnable {@ Override public void run () {for (int I = 0; I <100; ++ I) {System. out. println ("Welcome:" + I );}}}

 

Thread Analysis

The Thread class also implements the Runnable interface, so it implements the run () method in the interface.

When a Thread object is generated, if no name is specified for it, the Thread object name will be in the following format: Thread-number, which is an automatically added number, and shared by all the Thread objects because it is a static member variable.

  When the first method (inheriting Thread) is used to generate a Thread object, We need to override the run () method, because the run () method of the Thread class does nothing at this time.

  When the second method (implementing the Runnable interface) is used to generate a thread object, We need to implement the run () method of the Runnable interface, and then use new Thread (new MyRunnableClass () to generate the Thread object (MyRunnableClass has implemented the Runnable interface ), the run () method of the thread object calls the run () method of MyRunnableClass.

Stop thread

The death of a thread cannot end the run () method by calling the stop () command. The stop () method is insecure and has been discarded.

Recommended Method for stopping a thread: Set a flag variable, which is a loop in the run () method. The flag variable controls whether the loop continues to run or jumps out. If the loop jumps out, the thread ends.

As shown in the code example:

public class ControlThreadTest{    MyThreadClass r = new MyThreadClass();    Thread t = new Thread(r);    public void startThread()    {        t.start();    }    public void stopThread()    {        r.stopRunning();    }}class MyThreadClass implements Runnable{    private boolean flag = true;    @Override    public void run()    {        while (flag)        {            System.out.println("Do something.");        }    }    public void stopRunning()    {        flag = false;    }}
public class ControlThreadTest{    MyThreadClass r = new MyThreadClass();    Thread t = new Thread(r);    public void startThread()    {        t.start();    }    public void stopThread()    {        r.stopRunning();    }}class MyThreadClass implements Runnable{    private boolean flag = true;    @Override    public void run()    {        while (flag)        {            System.out.println("Do something.");        }    }    public void stopRunning()    {        flag = false;    }}

 


References

Shengsiyuan Zhang Long's Java SE series video tutorial.

 

Source: http://www.cnblogs.com/mengdd/archive/2013/02/16/2913637.html

 

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.