一、简单描述什么是进程和线程
1、进程:进程是程序运行资源分配的最小单位。
2、线程:线程是CPU调度的最小单位,必须依赖于进程而存在。
二、创建线程的几种方式
在JDK的源码Thread类中明确表示,创建线程的方式一共有两种:
- 一种是继承Thread类
- 另外一种是实现Runnable接口
如下图Thread类中的描述所示:
具体示例请看如下代码:
package cn.lspj.ch1.base;
/**
* 创建线程的方式
* 1、继承至Thread类
* 2、实现Runnable接口
*/
public class NewThread {
private static class UseThread extends Thread {
@Override
public void run() {
// TODO do my work
System.out.println("使用 extend Thread 方式创建的线程。。。 ");
}
}
private static class UseRunnable implements Runnable {
@Override
public void run() {
// TODO do my work
System.out.println("使用 implements Runnable 方式创建的线程。。。 ");
}
}
public static void main(String[] args) {
UseThread useThread = new UseThread();
useThread.start(); //启动线程
UseRunnable useRunnable = new UseRunnable();
new Thread(useRunnable).start(); // 启动线程
}
}
Thread 和 Runnable 的区别:
- Thread 才是 Java 里对线程的唯一抽象。
- Runnable 只是对任务(业务逻辑) 的抽象。
- Thread 可以接受任意一个 Runnable 的实例并执行。
特别注意,很多博客,在讲创建线程的方式时大部分说是三种,继承Thread、实现Runnable或者Callable接口,但是从本质上来讲Runnable和Callable可以归为一类。Callable可以指定返回值和检查异常处理,而Runnable不能。
备注:博主微信公众号,不定期更新文章,欢迎扫码关注。