线程
多线程解决是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() | 唤醒所有期待中的线程(同一期待阻塞池中的) |