Home > Java > javaTutorial > How to use global variables to terminate threads in Java?

How to use global variables to terminate threads in Java?

WBOY
Release: 2023-05-07 20:22:06
forward
982 people have browsed it

Instructions

1. Use custom global variables to terminate the thread. The termination method is relatively gentle. After getting the termination instruction, the current task needs to be executed before the thread will be terminated.

Use the global variable method to "stop talking" and then "talk" again.

2. Global variables control thread termination and will terminate the current task after the end.

Example

public class ThreadDemo {
 
    // 全局自定义变量
    private static boolean flag = false;
 
    public static void main(String[] args) throws InterruptedException {
        // 转账线程
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!flag) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("正在讲话...");
                }
                System.out.println("停止说话");
            }
        });
        t1.start();
 
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(310);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 改变变量的值来终止线程
                System.out.println("停止说话,有要事发生。");
                flag = true;
            }
        });
        t2.start();
        t1.join(); //对于用户线程而言,join()可以不写
        t2.join();
    }
 
}
Copy after login

The above is the detailed content of How to use global variables to terminate threads in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template