Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to terminate a thread using global variables in java

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report