停止线程以及Threadlocal

xiaoxiao2025-10-19  6

如何停止线程?

停止线程思路

1. 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。 2. 使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。 3. 使用interrupt方法中断线程。

代码:

class StopThread implements Runnable { private boolean flag = true; @Override public synchronized void run() { while (flag) { try { wait(); } catch (Exception e) { //e.printStackTrace(); stopThread(); } System.out.println("thread run.."); } } public void stopThread() { flag = false; } } public class StopThreadDemo { public static void main(String[] args) { StopThread stopThread1 = new StopThread(); Thread thread1 = new Thread(stopThread1); Thread thread2 = new Thread(stopThread1); thread1.start(); thread2.start(); int i = 0; while (true) { System.out.println("thread main.."); if (i == 300) { // stopThread1.stopThread(); thread1.interrupt(); thread2.interrupt(); break; } i++; } } }

ThreadLoca

什么是ThreadLoca

ThreadLocal提供一个线程的局部变量,访问某个线程拥有自己局部变量。

当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 ThreadLocal的接口方法 ThreadLocal类接口很简单,只有4个方法,我们先来了解一下:

void set(Object value)设置当前线程的线程局部变量的值。 public Object get()该方法返回当前线程所对应的线程局部变量。 public void remove()将当前线程局部变量的值删除,目的是为了减少内存的占用,该方法是JDK 5.0新增的方法。需要指出的是,当线程结束后,对应该线程的局部变量将自动被垃圾回收,所以显式调用该方法清除线程的局部变量并不是必须的操作,但它可以加快内存回收的速度。 protected Object initialValue()返回该线程局部变量的初始值,该方法是一个protected的方法,显然是为了让子类覆盖而设计的。这个方法是一个延迟调用方法,在线程第1次调用get()或set(Object)时才执行,并且仅执行1次。ThreadLocal中的缺省实现直接返回一个null。

案例:创建三个线程,每个线程生成自己独立序列号。

class Res { // 生成序列号共享变量 public static Integer count = 0; public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() { protected Integer initialValue() { return 0; }; }; public Integer getNum() { int count = threadLocal.get() + 1; threadLocal.set(count); return count; } } public class ThreadLocaDemo2 extends Thread { private Res res; public ThreadLocaDemo2(Res res) { this.res = res; } @Override public void run() { for (int i = 0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + "---" + "i---" + i + "--num:" + res.getNum()); } } public static void main(String[] args) { Res res = new Res(); ThreadLocaDemo2 threadLocaDemo1 = new ThreadLocaDemo2(res); ThreadLocaDemo2 threadLocaDemo2 = new ThreadLocaDemo2(res); ThreadLocaDemo2 threadLocaDemo3 = new ThreadLocaDemo2(res); threadLocaDemo1.start(); threadLocaDemo2.start(); threadLocaDemo3.start(); } }
转载请注明原文地址: https://www.6miu.com/read-5038203.html

最新回复(0)