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

How to use global variables to terminate threads in Java?

WBOY
WBOYforward
2023-05-07 20:22:06959browse

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();
    }
 
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete