多线程的创建、停止
时间:2020-09-17 17:10:06
收藏:0
阅读:35
1、多线程的创建方式
- 继承Thread类
- 实现runnable 接口,无返回值,无异常
- 实现callable接口,有返回值,有异常
- 线程池(此种方式,网上很多不算创建方式,但是个人觉得可以创建线程,所以我归进去)
1、1 继承Thread类
public static class MyThread extends Thread{ @Override public void run(){ System.out.println("继承Thread"); } }
1、2 实现runnable接口
public static class UseRunnable implements Runnable { @Override public void run() { System.out.println("i am runbable impl"); } }
1、3 实现callable接口
public static class UseCall implements Callable<String> { @Override public String call() throws Exception { return "Callable"; } }
1、4 main方法调用
public static void main(String[] args) { UseRunnable useRunnable = new UseRunnable(); new Thread(useRunnable).start(); /** *因为 Tread 源码中,不直接支持callable的方式,因此直接传入callable 是报错 *new Thread(useCall).start(); *以下为源码 * public Thread(Runnable target) { * init(null, target, "Thread-" + nextThreadNum(), 0); *} */ UseCall useCall = new UseCall(); FutureTask<String> futureTask = new FutureTask<>(useCall); new Thread(futureTask).start(); String s = null;//就是callable 的返回 try { s = futureTask.get(); //get方法是阻塞的 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println(s); }
注:几个线程的创建类,都用了static,是为了让我在main方法中使用
2、线程的停止
- 使用退出标志,使线程正常退出,也就是当 run() 方法完成后线程中止。
- 使用 stop(),resume(),suspend() 方法强行终止线程,但是不推荐使用这个方法,该方法已被弃用。此方法不释放资源
- interrupt() isInterrupted() ;static interrupted() ,这些方法都在Thread类中
2、1 继承类中使用
public static class EndThread extends Thread { public EndThread(String name) { super(name); } @Override public void run() { String threadName = Thread.currentThread().getName(); // while (true){ //如果此处 不对标记位进行处理 则不会中断 // System.out.println(String.format("线程【%S】,正在运行",threadName)); // // } while (!interrupted()) { //如果此处 不对标记位进行处理 则不会中断 System.out.println(String.format("线程【%S】,正在运行", threadName)); } System.out.println(String.format("线程【%S】的中断状态%S", threadName, interrupted())); } }
2、2 实现类中使用,此处只展示Runnable
/** * interrupted() 等方法是在Thread中存在,Runnable中不存在 * 下面演示如何在runnable中使用 */ public static class EndAble implements Runnable{ @Override public void run() { String threadName = Thread.currentThread().getName(); while (!Thread.currentThread().isInterrupted()) { //如果此处 不对标记位进行处理 则不会中断 System.out.println(String.format("线程【%S】,正在运行", threadName)); } System.out.println(String.format("线程【%S】的中断状态%S", threadName, Thread.interrupted())); } }
2、3 main方法中运行
public static void main(String[] args) { Thread endThread = new EndThread("endThread"); endThread.start(); try { Thread.sleep(2000); //停止是为了,监控中断状态 endThread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } }
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】,正在运行
线程【ENDTHREAD】的中断状态FALSE
评论(0)