A thread basis

Thread base

First, the understanding of java in the thread

1) java in the program are inherently multithreaded

public static void main(String[] args) {
    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
    for (ThreadInfo threadInfo : threadInfos) {
        System.out.println("["+threadInfo.getThreadId()+"]"+" "+threadInfo.getThreadName());
    }
}

/**
 * [6] Monitor Ctrl-Break
 * [5] Attach Listener
 * [4] Signal Dispatcher
 * [3] Finalizer
 * [2] Reference Handler
 * [1] main
 */

It can be seen that we just launched a main method, java virtual machine also gives us started six threads, so we say java in the program are inherently multithreaded

Two, java start in three ways multithreading

Learning from the following: https: //blog.csdn.net/m0_38075425/article/details/81606156

1. Thread class inheritance

To create and launch a multi-threaded through inheritance Thread class as follows:

1. Define a subclass of the Thread class, the class and override run () method, the method body of the run () method represents the thread needs to complete the task. Therefore, the run method is called thread of execution.

2, create an instance of a subclass of Thread, the thread object is created.

3, the calling thread object's start () method to start the thread.

private static class testThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 10 ; i++) {
            System.out.println(Thread.currentThread().getName()+" 执行了 "+i);
        }
    }

}
//测试
public static void main(String[] args) {
    new testThread().start();
    for (int i = 0; i < 10 ; i++) {
        System.out.println(Thread.currentThread().getName()+" 执行了 "+i);
    }
}

/**执行结果
main 执行了 0
Thread-0 执行了 0
main 执行了 1
main 执行了 2
main 执行了 3
Thread-0 执行了 1
main 执行了 4
Thread-0 执行了 2
main 执行了 5
Thread-0 执行了 3
main 执行了 6
Thread-0 执行了 4
main 执行了 7
Thread-0 执行了 5
Thread-0 执行了 6
main 执行了 8
*/

Thread0 can see the main thread and the thread of execution for loop alternately thread started successfully . This example program Thread1 class inherits the Thread class and override the run method, in the run method, we print out the name of the currently executing thread which thread is being executed, and executed many times, i use the member variables to record the number of executions . In the main function we create an instance of an object this thread, and the thread started by the start method, we can see that the implementation of preemptive thread is run. Although only create a thread instance, there are actually two threads thread of execution in the main thread running, as well as representatives of the main method.

  此外,我们还学习了线程的两个方法:

  1.Thread.currentThread(),是Thread类的静态方法,该方法总是返回当前正在执行的线程对象。

  2.getName():该方法是Thread类的实例方法,该方法返当前正在执行的线程的名称。在默认情况下,主线程的名称为main,用户启动的多线程的名称依次为Thread-0,Thread-1,Thread-3..Thread-n等。

2. implement Runnable

Runnable interface to create and implement multi-threaded steps to start as follows:

1. Define the Runnable interface implementation class, and override the run method of this interface, the method body run method is the same thread of execution of the thread

2. Create an instance of an object Runnable implementation class, and this instance of an object as a target to create a Thread class Thread, the Thread object is the real thread object.

3. Call the thread object's start () method to start the thread.

private static class testRunnable implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 10 ; i++) {
            System.out.println(Thread.currentThread().getName()+" 执行了 "+i);
        }
    }
}
//测试
public static void main(String[] args) {
    new Thread(new testRunnable()).start();
    for (int i = 0; i < 10 ; i++) {
        System.out.println(Thread.currentThread().getName()+" 执行了 "+i);
    }
}

Here particular attention to: main functions were not implemented Thread2 run method directly, but rather to fill Thread2 Thread, use the start method to start. Runnable implementation class contains the run method, only a thread of execution, and the actual thread object instance of the object is still the Thread, Thread object actually creating thread.

3. implement the interface Callable <>

Callable interface to create and implement multi-threaded steps to start as follows:

1. Callable defined class that implements the interface and call the method of rewriting the interface. Callable interface can be a generic type as the return value.

2. create an instance of the implementation class Callable, since not directly receive a Thread class Callable class as an argument. So we also need to create an object instance FutureTask to accept Callable instance of an object implementation class, then we in this instance of an object as a target to create Thread Thread class.

3. Call the thread object's start () method to start the thread, and we can get through a method call FutureTask object get () method returns a value

private static class testCallable implements Callable<String>{
    @Override
    public String call() throws Exception {
        System.out.println("I am implements Callable");
        return "CallResult";
    }
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask<String> futureTask = new FutureTask<>(new testCallable());
    new Thread(futureTask).start();
    System.out.println(futureTask.get());
}

/** 执行结果
I am implements Callable
CallResult
*/

Third, how to make thread-safe inside java stop working

In the original versions of the JDK, Thread class provides a thread termination method stop () method, but is now found in the JDK source code, stop () method has been abandoned. The main reason is: stop () method is too violent. Forced to terminate a thread being executed. So will cause some data inconsistencies.

public void Thread.interrupt()        //中断线程
public boolean Thread.isInterrupted() //判断线程是否中断
public static boolean Thread.interrupted() //判断是否被中断,并清除当前中断状态

Thread.interrupt () method is an instance method, it informs the target thread interrupt, the interrupt flag is set. Interrupt flag, indicating the current thread has been interrupted.

Thread.isInterrupted () method is an instance method, mainly to check whether the current thread is interrupted (by checking the interrupt flag), the return value is boolean type.

Thread.interrupted () method is used to determine whether the current thread has been interrupted, but at the same time clear the current thread's interrupt flag status.

test program

public static void main(String[] args) throws ExecutionException, InterruptedException {
    Thread thread = new Thread(){
        @Override
        public void run() {
            //中断处理逻辑
            while (true){
                System.out.println("The thread is waiting for interrupted!");
                /*if (Thread.currentThread().isInterrupted()){
                        System.out.println("The thread is interrupted!");
                        break;
                    }*/
            }
        }
    };
    thread.start();
    thread.interrupt();//中断线程
}

/**
The thread is waiting for interrupted!
The thread is waiting for interrupted!
The thread is waiting for interrupted!
The thread is waiting for interrupted!
The thread is waiting for interrupted!
The thread is waiting for interrupted!
.....
*/

If you can see the individual using the interrupt () method to interrupt the thread, then the thread did not actually break

public static void main(String[] args) throws ExecutionException, InterruptedException {
    Thread thread = new Thread(){
        @Override
        public void run() {

            while (true){
                System.out.println("The thread is waiting for interrupted!");
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("The thread is interrupted!");
                    break;
                }
            }
        }
    };
    thread.start();
    thread.interrupt();//中断线程
}

/** 执行结果
The thread is waiting for interrupted!
The thread is interrupted!
*/

Note: When a thread A thread calls the interrupt method B, if B thread being blocked (eg sleep, wait, etc.), then the time will throw InterruptExcpetion, while B thread's interrupt status will be reset false, this when two approaches:

First, when capturing InterruptException i.e. to catch the thread can interrupt status reset to true, and logging. By doing this, to maintain the thread B interrupt status unchanged.

Second, we will continue to throw an exception.

public static void main(String[] args) throws ExecutionException, InterruptedException {
    Thread thread = new Thread(){
        @Override
        public void run() {

            while (true){
                try {
                    sleep(2000);
                } catch (InterruptedException e) {
                    interrupt();
                    e.printStackTrace();
                }
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("The thread is interrupted!");
                    break;
                }
            }
        }
    };
    thread.start();
    thread.interrupt();//中断线程
}

Fourth, the threads of the life cycle

Figure 1. Life Cycle

The following is a life-cycle view of a thread:

2.start () and run () method

1.start () method to start a thread, truly multi-threaded operation. Then without waiting for the run method body code is completed, you can proceed directly to the following code; to start a thread by calling start Thread class () method, then this thread is in the ready state and is not running. Then this method calls the Thread class run () to complete its run operation, where the method run () is called thread body, which contains the contents of this thread to be executed, ending the Run method to run this thread to terminate. Then CPU rescheduling other threads.
2.run () call the method as a way ordinary method. Program or to execute the order, to wait after the implementation of the run method body, to proceed with the following code; if the head thread calls the object does not start () method, directly call run () method, the JVM thread stack did not join this thread , but in reality it is the main thread calls the run () method

Guess you like

Origin www.cnblogs.com/lee0527/p/11666754.html