1 概念
1.1 进程
进程是程序被操作系统内核加载到内存中后的一种内存中的数据结构,是系统进行资源分配和调度的基本单位。
思考:如何开启一个java进程?
每当执行 java命令(C:\Program Files\Java\jdk1.8.0_281\bin\java.exe)时,都会开启一个java进程。
java进程是否可以开启多个?
进程包括:
- 进程的指令序列(代码段)
- 进程号 pid
- 进程的内存空间(堆空间,栈空间),
- 系统资源(打开的文件描述符、网络IO Socket等)
什么是ava进程的堆空间,什么栈空间?
1.2 线程
- 在一个进程内部,可以有多个线程(每个线程对应一组指令序列,可由cpu执行),由操作系统进行调度
- 这些线程共享进程的堆内存,共享进程打开的系统资源
- 每个线程有自己的栈空间
1.3 主线程、子线程、守护(deamon)线程、非守护线程
- main线程结束后,java进程是否会结束?
取决与main方法中新开启的线程是不是 守护线程,如果不是守护线程,则java进程不会退出,如果是守护线程,则java程序会退出。
// 如果不是守护线程,则java进程不会退出
public class ThreadDemo01 {
public static void main(String[] args) {
System.out.println("main 方法执行开始");
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
});
//开启新的线程
thread.start();
System.out.println("main 方法执行结束");
}
}
// 如果是守护线程,则java程序会退出
public class ThreadDemo01 {
public static void main(String[] args) throws InterruptedException {
System.out.println("main 方法执行开始");
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
});
// 设置线程为守护(后台)线程
thread.setDaemon(true);
//开启新的线程
thread.start();
TimeUnit.SECONDS.sleep(3);
System.out.println("main 方法执行结束");
}
}
- java进程退出的条件?
java程序是否退出,取决于当前是否还有至少一个非守护线程存活。
1.4 main方法启动时,开启了几个线程?
private static void printAllThread() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
ThreadGroup topGroup = group;
// 遍历线程组树,获取根线程组
while (group != null) {
topGroup = group;
group = group.getParent();
}
// 激活的线程数再加一倍,防止枚举时有可能刚好有动态线程生成
int slackSize = topGroup.activeCount() * 2;
Thread[] slackThreads = new Thread[slackSize];
// 获取根线程组下的所有线程,返回的actualSize便是最终的线程数
int actualSize = topGroup.enumerate(slackThreads);
Thread[] atualThreads = new Thread[actualSize];
// 复制slackThreads中有效的值到atualThreads
System.arraycopy(slackThreads, 0, atualThreads, 0, actualSize);
System.out.println("Threads size is " + atualThreads.length);
for (Thread thread : atualThreads) {
System.out.println("Thread name : " + thread.getName());
}
}
private static void dumpAllThreadsInfo() {
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet) {
System.out.println("dumpAllThreadsInfo thread.name=" + thread.getName()
+ ";group=" + thread.getThreadGroup()
+ ";isDaemon=" + thread.isDaemon()
+ ";priority=" + thread.getPriority());
}
}
1.5 串行、并行、并发
串行执行任务
public class ThreadDemo02 {
public void task01() throws InterruptedException {
// 封装要执行的任务的代码逻辑
TimeUnit.SECONDS.sleep(1);
System.out.println("task01 is done");
}
public void task02() throws InterruptedException {
// 封装要执行的任务的代码逻辑
TimeUnit.SECONDS.sleep(2);
System.out.println("task02 is done");
}
public void task03() throws InterruptedException {
// 封装要执行的任务的代码逻辑
TimeUnit.SECONDS.sleep(3);
System.out.println("task03 is done");
}
// 如何执行这三个任务呢?
// 串行执行: 用一个线程把三个任务都执行完
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
final ThreadDemo02 threadDemo02 = new ThreadDemo02();
try {
threadDemo02.task01();
threadDemo02.task02();
threadDemo02.task03();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
System.out.println("main finished");
}
}
并行执行任务
/**
* 串行、并行(并发)
*/
public class ThreadDemo03 {
public void task01() throws InterruptedException {
// 封装要执行的任务的代码逻辑
TimeUnit.SECONDS.sleep(1);
System.out.println("task01 is done");
}
public void task02() throws InterruptedException {
// 封装要执行的任务的代码逻辑
TimeUnit.SECONDS.sleep(2);
System.out.println("task02 is done");
}
public void task03() throws InterruptedException {
// 封装要执行的任务的代码逻辑
TimeUnit.SECONDS.sleep(3);
System.out.println("task03 is done");
}
// 如何执行这三个任务呢?
// 并行执行: 用三个线程分别去执行三个任务,每个线程执行一个任务
public static void main(String[] args) throws InterruptedException {
final ThreadDemo03 threadDemo03 = new ThreadDemo03();
// 创建三个线程执行任务
final Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
final long start = System.currentTimeMillis();
threadDemo03.task01();
final long end = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":job finished,time used:" + (end - start));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
final Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
final long start = System.currentTimeMillis();
threadDemo03.task02();
final long end = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":job finished,time used:" + (end - start));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
final Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
try {
final long start = System.currentTimeMillis();
threadDemo03.task03();
final long end = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ":job finished,time used:" + (end - start));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 启动执行任务的线程
thread1.setName("thread1");
thread2.setName("thread2");
thread3.setName("thread3");
final long start = System.currentTimeMillis();
thread1.start();
thread2.start();
thread3.start();
// 让main线程等待其他三个线程都结束后再继续执行后面的代码
thread1.join(); // 等thread1结束
thread2.join();
thread3.join();
final long end = System.currentTimeMillis();
System.out.println("main finished,time used:"+(end-start));
}
}
2 创建线程
2.1 直接使用Thread类的构造函数
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
threadDemo02.task1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
2.2 继承Thread类覆盖run方法
/**
* 创建线程的方式
*/
public class ThreadDemo04 extends Thread{
// 覆盖run 方法
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ ": ThreadDemo04 started....");
}
public static void main(String[] args) {
final ThreadDemo04 threadDemo04 = new ThreadDemo04();
threadDemo04.start();
System.out.println(Thread.currentThread().getName()+ " main finished");
}
}
3 启动线程
3.1 启动线程的是run方法还是start方法?
public class ThreadDemo04 extends Thread{
// 覆盖run 方法
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+ ": ThreadDemo04 started....");
}
public static void main(String[] args) {
final ThreadDemo04 threadDemo04 = new ThreadDemo04();
// threadDemo04.start();
// 在当前线程中进行的一个对象的实例方法的调用而已,run就是一个普通的实例方法
// 属于当前线程内的串行方法调用
// threadDemo04.run();
// start方法,内部有特殊的逻辑,会让jvm跟底层操作系统交互,创建出一个新的线程
threadDemo04.start();
System.out.println(Thread.currentThread().getName()+ " main finished");
}
}
- start方法是启动线程的方法
- run方法定义了线程启动之后要执行的业务逻辑
- 如果在main线程中直接调用了线程对象的run方法,则相当于串行模式调用所有线程的run方法了,不会开启新的线程。
3.2 java真的能启动一个线程吗?
实际上线程的启动是由操作系统完成的,java语言中的Thread对象的start方法,最后会调用一个navtive方法start0,该方法会借由jvm进行底层的创建线程的系统调用,最后由操作系统内核创建出一个新的线程,并且把新线程的方法入口,设置为线程对象的run方法。private native void start0();
4 线程的调度
4.1 线程的调度由操作系统决定
4.2 多线程程序可能出现不同的执行结果
在没有采用任何同步措施的情况下,多线程程序的运行结果可能不同。
package com.qf.sy2103.thread01;
public class ThreadDemo04 {
public static void main(String[] args) {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t1 started ...");
}
});
final Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t2 started ...");
}
});
final Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("t3 started ...");
}
});
t1.start();
t2.start();
t3.start();
}
}
5 Thread对象API
- currentThread
- 获取到执行当前方法的Thread对象
- 是一个native方法
- isAlive ```java package com.qf.sy2103.thread01;
import java.util.concurrent.TimeUnit;
public class ThreadApiDemo {
public static void main(String[] args) throws InterruptedException {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().isAlive());
System.out.println("t1 started ...");
}
});
System.out.println(t1.isAlive());
t1.start();
TimeUnit.SECONDS.sleep(1);
System.out.println(t1.isAlive());
}
}
- sleep
- 让执行当前方法的线程,进入休眠状态,休眠方法参数指定的毫秒数。
- getid
```java
System.out.println("main 线程的id为:"+Thread.currentThread().getId());
System.out.println("t1 线程的id为:"+t1.getId());
- interrupt
中断失败的例子如下
public class ThreadDemo08 {
public static void main(String[] args) throws InterruptedException {
final Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"is running....");
}
}
});
thread1.setName("thread1");
thread1.start();
TimeUnit.SECONDS.sleep(2);
// 中断 thread1
thread1.interrupt();
}
}
public class ThreadInterruptDemo {
public static void main(String[] args) throws InterruptedException {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true){
System.out.println("t1 is busy ...");
// 监听线程自身是否被中断
if (Thread.currentThread().isInterrupted()) {
return;
}
}
}
});
t1.start();
TimeUnit.SECONDS.sleep(1);
t1.interrupt(); // 打断t1线程
}
}
// 打断 sleep中的线程 会抛出异常 InterruptedException
public class ThreadInterruptDemo {
public static void main(String[] args) throws InterruptedException {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true){
System.out.println("t1 is busy ...");
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
TimeUnit.SECONDS.sleep(1);
t1.interrupt(); // 打断t1线程
}
}
- setDeamon
设置线程是否为守护线程,默认是false 。java应用中必须要有至少一个非守护线程存活,程序才不会退出。
- join
- 在某个线程对象上调用join方法,会把执行当前方法的线程进行阻塞,等到目标线程执行完毕后才可以继续运行。
- 注意:调用join方法时,存在两个线程,一个是发起调用的线程,例如main线程,另外一个是执行join方法的线程对象所代表的线程A。执行的效果是让main线程进入等待,等待线程A执行完毕。 ```java package com.qf.sy2103.thread01;
import java.util.concurrent.TimeUnit;
public class ThreadJoinDemo {
public static void main(String[] args) throws InterruptedException {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
final Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
final long start = System.currentTimeMillis();
t1.start();
t2.start();
t1.join(); // 等待,直到 t1线程 运行结束
t2.join();
final long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
思考题:有三个线程A、B和C,希望以如下顺序执行,A先执行,A执行完之后B执行,B执行完之后C执行?
```java
/**
* 思考题:有三个线程A、B和C,希望以如下顺序执行,A先执行,A执行完之后B执行,B执行完之后C执行?
*/
public class ThreadDemo09 {
public static void main(String[] args) throws InterruptedException {
final Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+": 完成了任务A");
}
});
final Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
try {
threadA.join(); // 等待 A线程执行完成
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": 完成了任务B");
}
});
final Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
try {
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+": 完成了任务C");
}
});
threadA.setName("A");
threadB.setName("B");
threadC.setName("C");
// 启动三个线程
threadA.start();
threadB.start();
threadC.start();
}
}
6 线程的生命周期
6.1 Thread类中定义的线程状态
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;
}
6.2 生命周期状态转换
6.3 案例 利用jconsole观察线程状态
// 线程的NEW RUNNABLE TERMINATED
public class ThreadStateDemo {
public static void main(String[] args) throws InterruptedException {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
int a = 0;
for (int i = 0; i < 100000000 ; i++) {
a++;
}
System.out.println(a);
}
});
System.out.println("线程对象刚创建好:"+t1.getState());
t1.start();
Thread.sleep(1);
System.out.println("线程对象已经start:"+t1.getState());
Thread.sleep(2000);
System.out.println("线程已经运行完成:"+t1.getState());
}
}
/**
* 如果线程执行了 休眠方法 , Thread.sleep TimeUnit.SECONDS.sleep
* 则线程的状态是 TIMED_WAITING
*/
public class ThreadStateDemo3 {
public static void main(String[] args) throws InterruptedException {
final Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
TimeUnit.SECONDS.sleep(2);
System.out.println(t1.getState());
}
}
// 观察主线程和子线程的状态变化
public class ThreadStateDemo2 {
public static void main(String[] args) throws InterruptedException, IOException {
Thread mainThread = Thread.currentThread();
Object lock = new Object();
Thread subthread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
synchronized (lock) {
System.out.println("mainThread state is "+mainThread.getState());
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
subthread.start();
synchronized (lock) {
System.in.read();
System.out.println("subthread state is "+subthread.getState());
lock.wait();
}
}
}
观察主线程由waitting状态转换为Block状态
public class ThreadStateDemo2 {
public static void main(String[] args) throws InterruptedException, IOException {
Thread mainThread = Thread.currentThread();
Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
synchronized (lock) {
System.out.println("t1 mainThread state is "+mainThread.getState());
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
synchronized (lock) {
System.out.println("t2 mainThread state is "+mainThread.getState());
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
synchronized (lock) {
System.in.read();
System.out.println("t1 state is "+t1.getState());
System.out.println("t2 state is "+t2.getState());
lock.wait();
}
}
}
观察主线程由Timed-waitting状态转换为Block状态
public class ThreadStateDemo3 {
public static void main(String[] args) throws InterruptedException, IOException {
Thread mainThread = Thread.currentThread();
Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
synchronized (lock) {
System.out.println("t1 mainThread state is "+mainThread.getState());
Thread.sleep(3000);
System.out.println("t1 mainThread state is "+mainThread.getState());
lock.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
synchronized (lock) {
System.in.read();
System.out.println("t1 state is "+t1.getState());
// 主线程等待2s后醒来,继续争抢锁
// 注意:不是wait达到超时时间后就无条件继续向下执行代码!而是要继续去枪锁!
lock.wait(2000);
// 如果醒来后争抢锁失败,则线程直接进入blcok状态
// 当持有锁的线程释放锁后,主线程会继续去争抢锁,如果抢到,就可以继续执行
System.out.println("main finished ");
}
}
}