java multithreading Five: multithread-depth topics (elegant stop the thread)

Article Source https://www.jianshu.com/p/744c4e65a3b3

Articles corresponding video source: https://developer.aliyun.com/course/1012?spm=5176.10731542.0.0.6ef2d290hxQ4g0

Among the multi-line multi-threaded operation if you want to start using the Thread class start () method, and if needed to stop processing multiple threads, the Thread class provides the original stop () method, but these methods from JDK1. 2 version has been abolished, but until now no longer recommended, but in addition to stop () than there are several approaches have also been disabled:

  • Stop Multithreading: public final void stop ();
  • Destruction Multithreading: public void destroy ();
  • Hung thread: public final void suspend (), suspended;
  • Resume a suspended thread of execution: public final void resume ();
      why do away with these methods, the main reason is because these methods can lead to a thread deadlock, so from the beginning JDK1.2 are no longer recommended for use. So, if it is to achieve the thread needs to be stopped by a soft way.
    Example: Implementing Threads soft stop
public class ThreadDemo {
    public static boolean flag = true;
    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            long num = 0;
            while (flag) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在运行、num = " + num++);
            }
        }, "执行线程").start();
        Thread.sleep(200);//运行200毫秒
        flag = false;//停止线程
    }
}

 

In case there are other threads to control the content of this flag, this time to stop the thread is not to say stop to stop immediately, but will execute judgment on the content of the flag to complete.

Daemon thread

  Now suppose there is a bodyguard, then the bodyguard must have been alive when employers conduct guardian, employer dead, bodyguards useless. Therefore, multiple threads can be defined daemon threads, that is to say when or if other threads in the program now is still the main thread of execution, then the daemon threads will always exist, and runs in the background state.
  In the Thread class there is a method of operating a daemon thread provided:

  • Set a daemon thread: public final void setDaemon (boolean on);
  • Determine whether the daemon thread: public final boolean isDaemon ();
    Example: Using daemon thread
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Thread userThread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在运行、x = " + i);
            }
        }, "用户线程");//完成核心业务
        Thread deamonThread = new Thread(() -> {
            for (int i = 0; i < Integer.MAX_VALUE; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在运行、x = " + i);
            }
        }, "守护线程");//完成核心业务
        userThread.start();
        deamonThread.setDaemon(true);//设置为守护线程
        deamonThread.start();
    }
}
}

  It can be found all around daemon threads are threads around the user, if the program is finished, the daemon thread will disappear, the biggest in the entire JVM GC thread is a daemon thread.
  GC-threaded program execution will always exist, if the program is finished, GC thread will also disappear.

volatile keyword

  In a multithreaded definition, volatile keyword is mainly used on the property, this property represents a direct data operations, without performing the copying process copies. On some books on the wrong understanding of the properties of the synchronization.
  When the normal process variables tend to go through several steps as follows:

  • Acquiring data content variables;
  • Mathematical calculations for the variables;
  • After calculating the variables, saved to the original space;
      if a volatile keyword added attribute indicating the copy is not used, but the direct operation of the original variables, equivalent to saving a copy of a copy, the step of re-stored.

class MyThread implements Runnable {
    private volatile int ticket = 5;//直接内存操作
    @Override
    public void run() {
        synchronized (this){
            while (this.ticket > 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖票,ticket = " + this.ticket--);
            }
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        MyThread mt = new MyThread();
        new Thread(mt, "票贩子A").start();
        new Thread(mt, "票贩子B").start();
        new Thread(mt, "票贩子C").start();
    }
}

 

Published 52 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/YKWNDY/article/details/104850151