How to terminate a thread using global variables in java
This article mainly introduces the relevant knowledge of "how to use global variables to terminate threads in java". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use global variables to terminate threads in java" can help you solve the problem.
Description
1. Use a custom global variable to terminate the thread. The termination method is gentle, and after you get the termination instruction, you need to finish the current task before the thread is terminated.
After using the global variable method to "stop talking", there is another "talking".
2. Global variable control thread termination will cause the current task to be terminated after the end of the current task.
Example
Public class ThreadDemo {/ / global custom variable private static boolean flag = false Public static void main (String [] args) throws InterruptedException {/ / transfer thread Thread T1 = new Thread (new Runnable () {@ Override public void run () {while (! flag) {try {Thread.sleep (100) } catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("talking...");} System.out.println ("stop talking";}}); t1.start () Thread T2 = new Thread (new Runnable () {@ Override public void run () {try {Thread.sleep (310);} catch (InterruptedException e) {e.printStackTrace () } / / change the value of the variable to terminate the thread System.out.println ("stop talking, something important has happened.") ; flag = true;}}); t2.start (); t1.join (); / / for user threads, join () can not write t2.join ();}} that's all for "how to use global variables to terminate threads in java". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.