线程创建
1.Thread class ==== 继承Thread类
- 继承thread类
- 重写run方法,编写线程执行体
- 创建线程对象,调用start开启线程(调用run方法则体现不了多线程)
TestThread test = new TestThread();
test.start();
2.Runnable接口 ==== 实现Runnable接口
- 定义类实现Runnable接口
- 重写run()方法,编写线程执行体
- 创建线程对象,丢入Runnable接口实现类,然后调用Start开启线程
TestThread2 test2 = new TestThread2();
Thread thread = new thread(test2);
thread.start();
- 前两种一般用Runnable 方便共享资源
new Thread(test2,“name1”).start();
new Thread(test2,“name2”).start(); - java不允许多继承,因此实现了Runnable接口的类可以再继承其他类。
3.Callable接口 ==== 实现Callable接口(了解)
- 实现callable接口(有返回值类型)
- 重写call方法(抛出异常)
- 创建目标对象
- 创建执行服务
ExecutorService pool=Executors.newFixedThreadPool(nThread) - 提交执行:
- 获取结果:
- 关闭服务: