java 线程的创建以及根据线程名称获取线程、停止线程

一、线程的创建、运行、暂停

public class MyThread extends Thread {@Overridepublic void run() {try {// 睡眠三秒sleep(3000);// 逻辑代码System.out.println("逻辑代码......");} catch (InterruptedException e) {System.out.println("线程发生异常结束:" + Thread.currentThread().getName());System.out.println(e.getMessage());}}public static void main(String[] args) {// 创建线程MyThread myThread = new MyThread();// 启动线程myThread.start();}}

二、设置和获取线程名称

设置线程名称可以使用Thread类的如下方法:1、构造方法:public Thread (Runnable Target,String name)2、设置名字:public final void setName(String name)// 创建线程 并设置线程名称Thread myThread = new Thread("120");// 创建线程MyThread myThread = new MyThread();// 设置线程名称myThread.setName("110");获取线程名称:1、当前运行的线程名称:Thread.currentThread().getName()2、取得名字:public final String getName()System.out.println("获取当前运行的线程名称:" + Thread.currentThread().getName());System.out.println("获取线程名称:" + myThread.getName());

三、中断线程interrupt方法

对sleep中的线程进行interrupt()会抛异常,走catch方法,run方法正常结束,安全的停止线程。
可根据自己的业务进程设计停止线程的方式 ,不建议使用stop方法 ,因为存在数据的一致性问题,并且stop方法已经被java过期了。

杀线程

public static void main(String[] args) {// 创建线程MyThread myThread = new MyThread();// 设置线程名称myThread.setName("110");System.out.println("获取线程名称:" + myThread.getName());// 启动线程myThread.start();// 中断线程myThread.interrupt();}

四、获取所有线程

public class GetThreadName {public static void main(String[] args) {// 获取所有线程ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();int noThreads = currentGroup.activeCount();Thread[] lstThreads = new Thread[noThreads];currentGroup.enumerate(lstThreads);System.out.println("现有线程个数:" + noThreads);// 遍历线程for (int i = 0; i < noThreads; i++) {String threadName = lstThreads[i].getName();System.out.println("第" + i + "个线程名为:" + threadName);}}}

以上代码运行输出结果为(具体看现在运行了几个线程):
现有线程个数:2
第0个线程名为:main
第1个线程名为:Monitor Ctrl-Break

五、根据线程名称中断线程

public boolean killThreadByName(String name) {// 获取所有线程ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();int noThreads = currentGroup.activeCount();Thread[] lstThreads = new Thread[noThreads];currentGroup.enumerate(lstThreads);System.out.println("现有线程个数:" + noThreads);for (int i = 0; i < noThreads; i++) {String threadName = lstThreads[i].getName();System.out.println("第" + i + "个线程名为:" + threadName);// 中断指定的线程if (threadName.equals(name)) {System.out.println("中断线程:" + name);lstThreads[i].interrupt();return true;}}return false;}