程序由指令和数据组成,但这些指令要运行,数据要读写,就必须将指令加载至 CPU,数据加载至内存。在指令运行过程中还需要用到磁盘、网络等设备。进程就是用来加载指令、管理内存、管理 IO 的。
当一个程序被运行,从磁盘加载这个程序的代码至内存,这时就开启了一个进程。
一个线程就是一个指令流,将指令流中的一条条指令以一定的顺序交给 CPU 执行
一个进程之内可以分为一到多个线程。
二者对比
CPU | 时间片 1 | 时间片 2 | 时间片 3 |
---|---|---|---|
core | 线程 1 | 线程 2 | 线程 3 |
每个时间片只能由 1 个线程执行。
每个核(core)都可以调度运行线程,这时候线程可以是并行的。
并发(concurrent)是同一时间应对(dealing with)多件事情的能力
并行(parallel)是同一时间动手做(doing)多件事情的能力
共有 4 种方式可以创建线程,分别是:
public class MyThread extends Thread{
@Override
public void run(){
System.out.println("run");
}
public static void main(String[] args){
// 创建MyThread对象
MyThread t = new MyThread();
// 调用start方法启动线程
t.start();
}
}
public class MyRunnable implements Runnable{
@Override
public void run(){
System.out.println("run");
}
public static void main(String[] args){
// 创建MyRunnable对象
MyRunnable mr = new MyRunnable();
// 创建Thread对象
MyThread t = new MyThread(mr);
// 调用start方法启动线程
t.start();
}
}
public class MyCallable implements Callable<String>{
@Override
public String call()throws Exception{
System.out.println("run");
return "ok";
}
public static void main(String[] args) throws ExecutionException,InterruptedException{
// 创建MyRunnable对象
MyCallable mr = new MyCallable();
// 创建Future Task
FutureTask<String> ft = new FutureTask<String>(mr);
// 创建Thread对象
MyThread t = new MyThread(mr);
// 调用start方法启动线程
t.start();
// 调用ft的get方法获取线程执行结果;
String result = ft.get();
}
}
注意:
public class MyExecutors implements Runnable{
@Override
public void run(){
System.out.println("run");
}
public static void main(String[] args){
// 创建线程池对象
ExecutorService threadPool = Executors.newFixedPool(3);
threadPool.submit(new MyExecutors());
// 关闭线程池
threadPool.shutdown();
}
}
启动的线程的时候不可以使用 run 方法。
线程的状态可以参考 JDK 中的 Thread 类中的枚举 State
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
// 尚未启动的线程的线程状态
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
// 可运行线程的线程状态
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
// 线程阻塞等待监视器锁的线程状态
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
// 等待线程的线程状态
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
// 具有指定等待时间的等待线程的线程状态
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
// 已终止线程的线程状态,线程已完成执行
TERMINATED;
}
面试回答参考
新建(NEW)、可执行(RUNNABLE)、阻塞(BLOCKED)、等待(WAITING)、时间等待(TIMED_WAITING)、终止(TERMINATED)
可以使用线程中的 join 方法解决。
join() 等待线程运行结束。例如,调用 t.join(),阻塞调用此方法的线程,使其进入 timed_waiting 状态,直到线程 t 执行完成后,此线程再继续执行。
public class JoinTest {
public static void main(String[] args) {
// 创建线程对象
Thread t1 = new Thread(()->{
System.out.println("t1");
});
Thread t2 = new Thread(()->{
try {
t1.join(); // 加入线程t1,只有t1线程执行完毕后,再次执行该线程
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t2");
});
Thread t3 = new Thread(()->{
try {
t2.join(); // 加入线程t2,只有t2线程执行完毕后,再次执行该线程
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t3");
});
// 启动线程
t3.start();
t2.start();
t1.start();
}
}
// 执行结果
t1
t2
t3
共同点
wait(),wait(long) 和 sleep(long) 的效果都是让当前线程暂时放弃 CPU 的使用权,进入阻塞状态。
不同点
有三种方式可以停止线程
public class MyInterrupt1 extends Thread{
volatile boolean flag = false; // 线程执行的退出标记
@Override
public void run(){
while(!flag){
System.out.println("MyThread...run...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws InterruptedException {
// 创建MyThread对象
MyInterrupt1 t1 = new MyInterrupt1();
t1.start();
// 主线程休眠6秒
Thread.sleep(6000);
// 更改标记为true
t1.flag = true;
}
}
// 执行结果
MyThread...run...
MyThread...run...
public class MyInterrupt3 {
public static void main(String[] args) throws InterruptedException {
// 1. 打断阻塞的线程
Thread t1 = new Thread(()->{
System.out.println("t1 正在运行。。。");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "t1");
t1.start();
Thread.sleep(500);
t1.interrupt();
System.out.println(t1.isInterrupted());
// 2. 打断正常的线程
// Thread t2 = new Thread(()->{
// while(true){
// Thread current = Thread.currentThread();
// boolean interrupted = current.isInterrupted();
// if(interrupted){
// System.out.println("打断状态:"+ interrupted);
// break;
// }
// }
// },"t2");
// t2.start();
// Thread.sleep(500);
// t2.interrupt();
}
}
//1执行结果
t1 正在运行。。。
false
Exception in thread "t1" java.lang.RuntimeException: java.lang.InterruptedException: sleep interrupted
at MyInterrupt3.lambda$main$0(MyInterrupt3.java:9)
at java.lang.Thread.run(Thread.java:750)
Caused by: java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at MyInterrupt3.lambda$main$0(MyInterrupt3.java:7)
... 1 more
//2执行结果
打断状态:true