Java multi-threaded 01-- thread creation and termination, you will in several ways

This article will start began to introduce multi-threaded Java concurrency-related knowledge, thank you for concern and continued support. I am concerned about the number of public "side Java Code" to learn more Java-related knowledge.

Way to create threads

In Java, the usual way users take the initiative to create a thread, there are three, namely, inheritance Thread class , implement Runnable , by Callable 和 Future

Thread class inheritance

  • Thread class defined subclasses and override the run method of the class;
  • Call the thread object's start () method to start the thread.

By inheriting the Thread class Thread achieve, can not be shared between multiple threads thread class instance variables (need to create different Thread objects).

/**
 * 通过继承Thread实现线程
 */
public class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread.run()");
    }
}

MyThread myThread = new MyThread();
myThread.start();

Implement Runnable

  • If your class already extends another class, it can not directly extends Thread, this time, you can achieve a Runnable interface;
  • Call the thread object's start () method to start the thread.
/**
 * 通过实现Runnable接口实现的线程类
 */
public class RunnableTest implements Runnable {
    @Override
    public void run() {
        System.out.println("RunnableTest.run()");
    }

    public static void main(String[] args) {
        RunnableTest runnableTest = new RunnableTest() ;
        Thread thread = new Thread(runnableTest);
        thread.start();
    }
}

By Callable, Future

Thread and Runnable can be seen in two ways, either way does not support return values , and can not declare an exception is thrown .

And this is achieved Callable two interfaces, interfaces as Callable upgraded Runable interface, which provides a Call () method as executable threads, while allowing a return value.

Callable object but not directly as a target Thread object, we can use the packaging Callable FutureTask class object, which object encapsulates FutureTask Callable object of the call () Returns the value of the method.

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CallableTest {
    public static void main(String[] args) {
        CallableTest callableTest = new CallableTest() ;
        //因为Callable接口是函数式接口,可以使用Lambda表达式
        FutureTask<String> task = new FutureTask<Integer>((Callable<String>)()->{
          System.out.println("FutureTask and Callable");
          return "hello word";
        });

       try{
           System.out.println("子线程返回值 : " + task.get());
        } catch (Exception e){
           e.printStackTrace();
        }
    }
}

Threading method of termination

In addition to the normal end of the thread can also terminate a particular way by a thread, the thread termination There are three common ways: using the exit sign exit thread , ** Interrupt method ends of threads , STOP method terminates the thread **.

Use the exit sign exit thread

The most commonly used way of its implementation are: the definition of a type of boolean flag in the thread run () method in accordance with this flag is true or false to determine whether to exit, this task is usually placed in run ( ) of a while loop process performed.

public class ThreadSafe extends Thread {
    public volatile boolean exit = false;
    public void run() {
        while (!exit){
            //do work
        }
    }

    public static void main(String[] args) throws Exception  {  
        ThreadFlag thread = new ThreadFlag();  
        thread.start();  
        sleep(5000); // 主线程延迟5秒  
        thread.exit = true;  // 终止线程thread    
        thread.join();  
        System.out.println("线程退出!");  
    }
}

Interrupt way to end a thread

Use interrupt () method to interrupt the thread, there are two cases:

  1. The thread is blocked . As used SLEEP, when the synchronization lock wait, socket of the receiver, accept the like, will make the thread is blocked.使用 interrupt 方法结束线程的时候,一定要先捕获 InterruptedException 异常之后通过 break 来跳出循环,才能正常结束 run 方法。
public class ThreadInterrupt extends Thread {  
    public void run()  {  
        try {  
            sleep(50000);  // 延迟50秒  
        }  
        catch (InterruptedException e) {  
            System.out.println(e.getMessage());  
        }  
    }  
    public static void main(String[] args) throws Exception  {  
        Thread thread = new ThreadInterrupt();  
        thread.start();  
        System.out.println("在50秒之内按任意键中断线程!");  
        System.in.read();  
        thread.interrupt();  
        thread.join();  
        System.out.println("线程已经退出!");  
    }  
}
  1. No thread is blocked . Use isInterrupted () interrupt flag judgment threads to exit the loop. When using the interrupt () method, the interrupt flag will be set to true, and use self-defined flags to control the cycle is the same reason.
public class ThreadSafe extends Thread {
    public void run() {
        while (!isInterrupted()) { //非阻塞过程中通过判断中断标志来退出
            try {
                Thread.sleep(5*1000);//阻塞过程捕获中断异常来退出
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;//捕获到异常之后,执行 break 跳出循环
            }
        }
    }
}

stop method stops the thread

Stop method could be forced to terminate or suspend the running thread. We can use the following code to terminate the thread:

thread.stop();

Using stop is unsafe , the main impact point as follows:

  1. After thread.stop () call to create a child thread thread will throw ThreadDeatherror error;
  2. Call to stop child thread will release all the locks held. Causing the thread held by the sudden release of all locks (uncontrollable), then it is possible to render the protected data inconsistencies.

to sum up

  • Thread creation : recommended creating a thread using Runnable or Callable way, compared to inheritance, interface implementation can be more flexible, not limited to Java's single inheritance.
  • Thread termination : terminate the thread recommended Interrupt flag or terminate, stop thread-safe manner, easily lead to inconsistent data.

Guess you like

Origin www.cnblogs.com/weechang/p/12499987.html