线程
多线程处理是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() | 唤醒所有等待中的线程(同一等待阻塞池中的) |
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。