线程
多线程解决是 java 语言的重要特点之一, 在 java 中有着很重要的位置.
三种创立办法
-
继承 Thread 父类
继承 Thread 父类, 每 new 一个子类对象就是创立一个线程.
class ThreadTest{public static void main(String[] args) {testThread thread = new testThread(); thread.start();// 输入 --> 继承 Thread 类创立的线程} } class testThread extends Thread{ @Override public void run() {System.out.println("继承 Thread 类创立的线程"); } } // 局限性: 单继承限度
-
实现 Runnable 接口 (个别应用)
class ThreadTest{public static void main(String[] args) {testThread2 thread2 = new testThread2(); new Thread(thread2).start();// 输入 --> 实现 Runnable 类创立的 Thread2 Runnable thread3 = ()->System.out.println("Lambda 表达式"); new Thread(thread3).start();// 输入 --> Lambda 表达式} } class testThread2 implements Runnable{ @Override public void run() {System.out.println("实现 Runnable 类创立的 Thread2"); } } // 防止了单继承的限度, 然而操作线程有点繁琐.
-
实现 Callable
class ThreadTest{public static void main(String[] args) throws ExecutionException, InterruptedException { // 将 testThread 对象当做指标对象来与 FutureTask 关联 FutureTask<String> result = new FutureTask<String>(new testThread()); // 将 FutureTask 的对象当做指标对象创立线程, FutureTask 实现 RunnableFuture,RunnableFuture 继承 Runnable Thread thread = new Thread(result); thread.start(); // 取到 call 办法的返回值并打印 --> 执行结束 System.out.println(result.get()); } } class testThread implements Callable<String> { @Override public String call() throws Exception {System.out.println("实现 Callable 接口创立的线程"); // 输入 --> 实现 Callable 接口创立的线程 return "执行结束"; } }
- 继承 Thread 创立线程是间接 new Thread 子类对象, 每个线程都是一个独立的子类对象
- 实现 Runnable 接口和 Callable 接口创立线程都是将它们的子类对象作为指标对象 target, 而后 new Thread(target). 创立进去的线程共用一个指标对象, 适宜多线程解决同一份资源的状况.
- Callable 接口的 call() 和 Runnable 的 run() 都是线程执行调用的办法, 但 call() 性能更多一点, 能够抛出异样, 能够有返回值
线程生命周期
常见 API
办法 | 阐明 |
---|---|
Thread.sleep(long n) | 休眠 n 毫秒, 工夫到后线程主动进入就绪状态 |
Thread.yield() | 以后线程放弃 CPU 执行权, 不肯定胜利 |
Thread.currentThread() | 返回对以后线程对象的援用 |
t.join() | 在 A 线程中调用 b.join(), 则 A 线程阻塞, 直到 B 线程执行结束, 也能够设置工夫参数, 工夫到之后不论 B 是否执行结束都会唤醒 A. |
t.getId/Name/Priority/State() | 获取线程的 ID/name/ 优先级 / 状态 |
t.isAlive() | 检测线程是否还活着 |
obj.wait() | 期待, 能够给参数值, 工夫到后主动进入就绪, 不给值就须要强制唤醒 |
obj.notify() | 随机唤醒一个期待中的线程 (同一期待阻塞池中的) |
obj.notifyAll() | 唤醒所有期待中的线程 (同一期待阻塞池中的) |