1、线程的初步认识java
一、区分进程、程序和线程多线程
程序:没有执行的指令和相关数据的集合,没有任何运行的含义。线程
进程:正在运行的程序就是一个进程,当你运行一个程序,也就启动了一个进程。进程是系统进行资源分配和调度的独立单位。code
线程:线程是进程中的一个执行单元,是CPU调度和分配的基本单元。继承
二、多线程接口
能够简单的理解为一个程序同时执行多个任务,每个任务就是一个线程,多个线程之间是共享数据的。进程
2、线程的状态资源
线程有五大状态:建立、就绪、运行、阻塞和死亡。关系如图所示:开发
3、线程的建立方式class
一、继承Thread类
public class TestThread { public static void main(String[] args) { Thread thread = new MyThread(); thread.start(); } } class MyThread extends Thread { public void run() { System.out.println("继承Thread类建立方法"); } }
二、实现Runnable接口
public class TestRunnable { public static void main(String[] args) { Thread thread = new Thread(new TestThread()); thread.start(); } } class TestThread implements Runnable { public void run() { System.out.println("实现runnable接口"); } }
三、使用内部类建立线程
public class InnerThread { public static void main(String[] args) { new Thread() { public void run() { System.out.println("内部类方式实现建立"); } }.start(); } }
在实际开发中,实现Runnable接口的方式建立线程使用的更多。