线程
- 进程与线程的区别
1、进程:是系统进行分配和管理资源的基本单位
2、线程:进程的一个执行单元,是进程内调度的实体、是CPU调度和分派的基本单位,是比进程更小的独立运行的基本单位。线程也被称为轻量级进程,线程是程序执行的最小单位
3、一个程序至少一个进程,一个进程至少一个线程
4、进程有自己的独立地址空间,每启动一个进程,系统就会为它分配地址空间,建立数据表来维护代码段、堆栈段和数据段,这种操作非常昂贵。 而线程是共享进程中的数据的,使用相同的地址空间,因此CPU切换一个线程的花费远比进程要小很多,同时创建一个线程的开销也比进程要小很多。 线程之间的通信更方便,同一进程下的线程共享全局变量、静态变量等数据,而进程之间的通信需要以通信的方式进行。 如何处理好同步与互斥是编写多线程程序的难点。 多进程程序更健壮,进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响, 而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程之间没有单独的地址空间,所以可能一个线程出现问题,进而导致整个程序出现问题
- 线程的状态及其相互转换
1、初始(NEW):新创建了一个线程对象,但还没有调用start()方法
2、运行(RUNNABLE):处于可运行状态的线程正在JVM中执行,但它可能正在等待来自操作系统的其他资源,例如处理器
3、阻塞(BLOCKED):线程阻塞于synchronized锁,等待获取synchronized锁的状态。
4、等待(WAITING):Object.wait()、join()、 LockSupport.park(),进入该状态的线程需要等待其他线程做出一些特定动作(通知或中断)
5、超时等待(TIME_WAITING):Object.wait(long)、Thread.join()、LockSupport.parkNanos()、LockSupport.parkUntil,该状态不同于WAITING,它可以在指定的时间内自行返回
6、终止(TERMINATED):表示该线程已经执行完毕
- 运行状态
public class ThreadStateDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
});
thread.start();
}
}
# cmd -> jconsole -> 查看状态
- 案例2: 超时等待和阻塞
public class ThreadStateDemo {
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
Thread thread = new Thread(()->{
synchronized (obj) {
try {
Thread.sleep(100000000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
Thread.sleep(2000L);
Thread thread2 = new Thread(()->{
synchronized (obj) {
}
});
thread2.start();
}
}
- 案例3:等待
public class ThreadStateDemo {
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
Thread thread = new Thread(()->{
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
-
状态间转换
-
创建线程
1、继承Thread,并重写父类的run方法
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.setName("线程demo");
myThread.start();
}
}
2、实现Runable接口,并实现run方法
public class MyRunable implements Runnable,Serializable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunable());
thread.setName("xdclass");
thread.start();
}
}
# 实际开发中,选第2种:java只允许单继承 增加程序的健壮性,代码可以共享,代码跟数据独立
- 其他创建线程方式
1、使用匿名内部类
public class MyThread {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
thread.start();
}
}
2、Lambda表达式
public class Lambda {
public static void main(String[] args) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}).start();
}
}
3、线程池
public class ThreadPool {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(()->{
System.out.println(Thread.currentThread().getName());
});
}
}
- 线程的挂起跟恢复
1、挂起线程定义: 线程的挂起操作实质上就是使线程进入“非可执行”状态下,在这个状态下CPU不会分给线程时间片,进入这个状态可以用来暂停一个线程的运行。 在线程挂起后,可以通过重新唤醒线程来使之恢复运行
2、挂起线程的作用: cpu分配的时间片非常短、同时也非常珍贵。避免资源的浪费
3、挂起线程步骤:
3.1、被废弃的方法:
thread.suspend() 该方法不会释放线程所占用的资源。如果使用该方法将某个线程挂起,则可能会使其他等待资源的线程死锁;thread.resume() 方法配合suspend()方法使用,用于恢复
3.2、推荐使用的方法:
wait() 暂停执行、放弃已经获得的锁、进入等待状态
notify() 随机唤醒一个在等待锁的线程
notifyAll() 唤醒所有在等待锁的线程,自行抢占cpu资源
4、何时挂起线程:等待某些未就绪的资源时挂起,直到notify方法被调用
- 挂起线程代码案例
public class SuspendDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行run方法,准备调用suspend方法");
//挂起线程
Thread.currentThread().suspend();
System.out.println(Thread.currentThread().getName()+"执行run方法,调用suspend方法结束");
}
public static void main(String[] args) throws InterruptedException {
// 创建线程
Thread thread = new Thread(new SuspendDemo());
// 启动线程,会执行run方法,并调用suspend方法挂起
thread.start();
// 休眠3秒
Thread.sleep(3000L);
//对线程进行唤醒操作
thread.resume();
}
}
- 挂起线程,造成死锁案例
public class DeadDemo implements Runnable{
private static Object object = new Object();
@Override
public void run() {
// 使用synchronized方法持有资源
synchronized (object) {
System.out.println(Thread.currentThread().getName()+"占用资源");
// 挂起线程,该方法不会释放线程所占用的资源
Thread.currentThread().suspend();
}
// 挂起线程后就表示释放资源
System.out.println(Thread.currentThread().getName()+"释放资源");
}
public static void main(String[] args) throws InterruptedException {
// 创建线程,执行run方法,挂起、休眠1秒、恢复
Thread thread = new Thread(new DeadDemo(),"对比线程");
thread.start();
Thread.sleep(1000L);
thread.resume();
// 再创建1个线程,执行run方法,挂起、恢复
Thread deadThread = new Thread(new DeadDemo(),"死锁线程");
deadThread.start();
deadThread.resume();
}
}
- 挂起线程案例2
public class WaitDemo implements Runnable {
private static Object object = new Object();
private static Object waitObj = new Object();
@Override
public void run() {
// 使用synchronized方法持有资源
synchronized (waitObj) {
System.out.println(Thread.currentThread().getName()+"占用资源");
try {
// 挂起
waitObj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"释放资源");
}
public static void main(String[] args) throws InterruptedException {
// 创建线程,执行run方法,挂起线程
Thread thread = new Thread(new WaitDemo(),"对比线程");
thread.start();
// 创建线程,执行run方法,挂起线程,休眠3秒
Thread thread2 = new Thread(new WaitDemo(),"对比线程2");
thread2.start();
Thread.sleep(3000L);
// 唤醒所有线程
synchronized (waitObj) {
waitObj.notify();
}
}
}
- 线程中断
1、stop() 废弃方法,开发中不要使用。因为一调用,线程就立刻停止,此时有可能引发相应的线程安全性问题
2、推荐使用Thread.interrupt方法
3、自行定义一个标志,用来判断是否继续执行
# 使用stop方法中断线程
public class Demo implements Runnable {
@Override
public void run() {
// 线程没有中断就一直执行while方法
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Demo());
thread.start();
Thread.sleep(2000L);
thread.stop(); // 中断线程
}
}
# 使用stop方法中断线程的不安全案例
public class UnsafeWithStop extends Thread {
private int i = 0;
private int j = 0;
@Override
public void run() {
i++;
try {
sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
j++;
}
public void printf() {
System.out.println("i的值=======》"+i);
System.out.println("j的值=======》"+j);
}
public static void main(String[] args) throws InterruptedException {
// 启动线程
UnsafeWithStop unsafeWithStop = new UnsafeWithStop();
unsafeWithStop.start();
Thread.sleep(1000L);
// 中断线程
unsafeWithStop.stop();
unsafeWithStop.printf();
}
}
# 使用interrupt方法中断线程案例
public class InterruptDemo implements Runnable {
@Override
public void run() {
// 线程没有中断就一直执行while方法
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new InterruptDemo());
thread.start();
Thread.sleep(1000L);
// 使用interrupt方法中断线程
thread.interrupt();
}
}
# 自定义标志指定线程是否执行
public class MyInterruptDemo implements Runnable {
private static volatile boolean FLAG = true;
@Override
public void run() {
while (FLAG) {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new MyInterruptDemo());
thread.start();
Thread.sleep(1000L);
FLAG = false;
}
}
- 线程优先级
1、线程的优先级告诉程序该线程的重要程度有多大。如果有大量线程都被堵塞,都在等候运行,程序会尽可能地先运行优先级的那个线程。 但是,这并不表示优先级较低的线程不会运行。若线程的优先级较低,只不过表示它被准许运行的机会小一些而已
2、线程的优先级设置可以为1-10的任一数值,Thread类中定义了三个线程优先级,分别是:MIN_PRIORITY(1)、NORM_PRIORITY(5)、MAX_PRIORITY(10),一般情况下推荐使用这几个常量,不要自行设置数值
3、不同平台,对线程的优先级的支持不同。 编程的时候,不要过度依赖线程优先级,如果你的程序运行是否正确取决于你设置的优先级是否按所设置的优先级运行,那这样的程序不正确
# 代码案例
public class PriorityDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
while (true) {
System.out.println(Thread.currentThread().getName());
}
}, "线程1");
Thread thread2 = new Thread(() -> {
while (true) {
System.out.println(Thread.currentThread().getName());
}
}, "线程2");
// 设置线程优先级
thread.setPriority(Thread.MIN_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY);
thread.start();
thread2.start();
}
}
- 守护线程
1、线程分类: 用户线程、守护线程;守护线程:任何一个守护线程都是整个程序中所有用户线程的守护者,只要有活着的用户线程,守护线程就活着。当JVM实例中最后一个非守护线程结束时,也随JVM一起退出
2、守护线程的用处:jvm垃圾清理线程
3、建议: 尽量少使用守护线程,因其不可控不要在守护线程里去进行读写操作、执行计算逻辑
# 代码案例
public class DaemonThreadDemo implements Runnable{
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
// 启动1个线程
Thread thread = new Thread(new DaemonThreadDemo());
// 设置为守护线程
thread.setDaemon(true);
thread.start();
Thread.sleep(2000L);
}
}