Java多线程系列 - 多线程启动后如何关闭多线程?多线程的关闭

多线程的关闭

 多线程的启动是一个重要的问题,大部分的多线程都是运行在一个死循环中的,所以关闭多线程也是一个很重要的问题。因为线程就是进程中处理问题的分支,其共享该进程中的资源,可以通过共享的某种资源来进行控制线程的开关,同样java本身也存在着关闭多线程的方法,所以我们来梳理一下。

关闭的方法

  • 通过进程中共享的某种资源控制

我们通过共享的静态属性running来控制线程中循环是否进行,来判断是否可以关闭线程。下面是实现的代码,可以自己跑一跑。

/*
*       如何让子线程停下来
*       通过使用共享变量进行控制
* */

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

class MyThread extends Thread{
    @Override
    public void run() {
        while(Main.running){
            // 设置休眠,每秒打印一次
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程在打印中");
        }
    }
}

public class Main {
    public static boolean running = true;
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        MyThread myThread = new MyThread();
        myThread.start();
        
        String str = scanner.nextLine();
        running = false;
    }
}

我们通过静态属性running来控制多线程的开关,不妨将代码复制下来,测试一下

  • 通过Thread类内部实现的方法来关闭多线程

在每个Thread对象中存在一个类似running的属性,用来控制线程是否进行,所以每个对象中都存在一个interrupt的方法,可以让其它线程来调用,当某个线程的该方法被调用时,则就修改了类似于running的属性,此时就将线程关闭。

代码展示

/*
 *   关闭多线程2
 *
 *       通过多线程对象中的interrupt方法来关闭多线程
 * */

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

class MyThread2 extends Thread {
    @Override
    public void run() {

        while (!this.isInterrupted()) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
            System.out.println("子线程打印中...");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread2 myThread2 = new MyThread2();
        myThread2.start();

        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        
        myThread2.interrupt();
    }
}

这里的要说一下这里用到的三个方法isinterrupted和interrupt和interrupted方法

  • isinterrupted方法的返回值是boolean类型,返回值为true则表示线程已经停止,否则为没停止,用于查看第三方的线程是否关闭,值会被保留
  • interrupt方法的返回值是void类型,调用后会将线程关闭
  • interrupted方法的返回值是boolean类型,调用后不会包保留。用于线程自己查看是否自己被关闭。
方法名称返回值类型返回值说明
isinterruptedbooleantrue或者false关闭了or没关闭
interruptvoid调用后会将线程停止
interrputedbooleantrue或者false用于线程自己查看是否被关闭

这里要注意的是,其他线程调用interrupt方法,只会对线程是否关闭有建议权,并不能强制线程关闭

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,您的问题是关于Java多线程的存钱取钱问题。这是一个经典的多线程同步问题,可以通过使用synchronized关键字来实现线程安全。下面是一个简单的示例代码: ```java public class BankAccount { private int balance; public BankAccount(int balance) { this.balance = balance; } public synchronized void deposit(int amount) { balance += amount; System.out.println("Deposit successful. Balance: " + balance); } public synchronized void withdraw(int amount) { if (balance < amount) { System.out.println("Withdraw failed. Insufficient balance."); return; } balance -= amount; System.out.println("Withdraw successful. Balance: " + balance); } } public class Main { public static void main(String[] args) { BankAccount account = new BankAccount(1000); // Create two threads to simulate deposit and withdraw Thread depositThread = new Thread(() -> { for (int i = 0; i < 5; i++) { account.deposit(100); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread withdrawThread = new Thread(() -> { for (int i = 0; i < 5; i++) { account.withdraw(200); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); depositThread.start(); withdrawThread.start(); } } ``` 在这个示例代码中,我们创建了一个银行账户类BankAccount,并在其中实现了deposit和withdraw方法,并使用synchronized关键字来保证线程安全。 在main方法中,我们创建了两个线程来模拟存款和取款操作,每个线程执行5次操作。我们使用Thread.sleep方法来模拟每个操作之间的间隔,以便更好地观察多线程操作的结果。 当多个线程同时访问BankAccount对象的deposit和withdraw方法时,synchronized关键字可以确保每个方法只能被一个线程访问,从而避免了竞争条件和数据不一致的问题。 希望这个示例代码能够回答您的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

友人和他的朋友们

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值