1、概念

  1. 线程是JVM(Java虚拟机)调度的最小单元,也叫做轻量级进程,~~进程是由线程组成~~(进程包含多个线程),线程拥有私有的程序技术器以及栈,并且能够访问堆中的共享资源。<br />这里提出一个问题,为什么要用多线程?有一下几点,
  1. 首先,随着cpu核心数的增加,计算机硬件的并行计算能力得到提升,而同一个时刻一个线程只能运行在一个cpu上,那么计算机的资源被浪费了,所以需要使用多线程。
  2. 其次,也是为了提高系统的响应速度,如果系统只有一个线程可以执行,那么当不同用户有不同的请求时,由于上一个请求没处理完,那么其他的用户必定需要在一个队列中等待,大大降低响应速度,所以需要多线程。

这里继续介绍多线程的几种状态:
JAVA多线程 - 图1
这里可以看到多线程有六种状态,分别是

  1. 就绪态,
  2. 运行态,
  3. 死亡态,
  4. 阻塞态,
  5. 等待态,
  6. 超时等待态

各种状态之间的切换如上图所示。这里的状态切换是通过synchronized锁下的方法实现,对应的Lock锁下的方法同样可以实现这些切换。

2、线程的创建

  1. 线程的创建有两种方式,第一种是继承Thread类,第二种是实现Runnable接口。第一个代码:
  1. class MyThread extends Thread{//继承了Thread类
  2. int j=20;
  3. //继承了Thread类就要重写run()方法
  4. @Override
  5. public void run(){
  6. for (int i = 0; i < 20; i++) {
  7. try {
  8. Thread.sleep(100);//这了休眠了0.1秒
  9. } catch (InterruptedException e) {
  10. // TODO Auto-generated catch block
  11. e.printStackTrace();
  12. }
  13. System.out.println(this.getName()+",i="+j--);
  14. }
  15. }
  16. }

然后main函数中创建:

  1. public class Main {
  2. public static void main(String[] args) {
  3. MyThread myThread=new MyThread();//创建线程对象
  4. myThread.start();//线程对象的运行
  5. }
  6. }

第二种方法:

  1. class MyRunnable implements Runnable{
  2. int j=20;
  3. @Override
  4. public void run() {
  5. for (int i = 0; i < 20; i++) {
  6. System.out.println(Thread.currentThread().getName()+",j="+this.j--);
  7. }
  8. }
  9. }

main函数中:

  1. public class Main {
  2. public static void main(String[] args) {
  3. // write your code here
  4. MyRunnable myRunnable = new MyRunnable();//创建线程对象
  5. Thread t1 = new Thread(myRunnable);//创建对象1
  6. Thread t2 = new Thread(myRunnable);//创建对象2
  7. t1.start();
  8. t2.start();
  9. }
  10. }

这就是两种创建线程的方法,在这两种方法中第二种方法时一般情况下的用法,因为继承只能继承一个类,但是可以实现多个接口,这样拓展性更好。
笔者建议:能接口解决的绝不继承。

3、线程安全测试

  1. 线程安全是多线程编程中经常需要考虑的一个问题,线程安全是指多线程环境下多个线程可能会同时对同一段代码或者共享变量进行执行,如果每次运行的结果和单线程下的结果是一致的,那么就是线程安全的,如果每次运行的结果不一致,那么就是线程不安全的。这里对线程安全做一个测试:<br />问题:什么是线程安全?
  1. class MyRunnable implements Runnable{
  2. static int j=10000;
  3. @Override
  4. public void run() {
  5. for (int i = 0; i < 5000; i++) {
  6. System.out.println(j--);
  7. }
  8. }
  9. }

main函数中:

  1. MyRunnable myRunnable = new MyRunnable();
  2. Thread t1 = new Thread(myRunnable);
  3. Thread t2 = new Thread(myRunnable);
  4. t1.start();
  5. t2.start();

可以看到,这里同时两个线程同时对共享变量j进行访问,并且减1,但最后的输出结果却是:

  1. 48
  2. 47
  3. 46

并且多次执行程序的结果还不一致,这就是线程不安全的情况,通过加锁可以保证线程安全。

4、锁

  1. java中有两种锁,一种是重量级锁synchronizedjdk1.6经过锁优化加入了偏向锁和轻量级锁,一种是JUC并发包下的Lock锁,synchronized锁也称对象锁,每个对象都有一个对象锁。这里通过加锁的方式实现线程安全:<br />代码:
  1. class MyRunnable implements Runnable{
  2. static int j=10000;
  3. @Override
  4. public synchronized void run() {
  5. for (int i = 0; i < 5000; i++) {
  6. System.out.println(j--);
  7. }
  8. }
  9. }

main中创建两个线程,测试多次的结果都是:

  1. 3
  2. 2
  3. 1

说明实现的线程安全,因为当加锁过后,每次只能有一个线程访问被加锁的代码,这样就不会出现线程安全了。

5、sleep

  1. sleep是让当前线程睡眠,睡眠一段时间后重新获取到cpu的使用权。<br />代码如下:
  1. try {
  2. Thread.sleep(100);
  3. } catch(InterruptedException e) {
  4. // TODO Auto-generated catch block
  5. e.printStackTrace();
  6. }

这里表示线程会睡眠100ms后再次到就绪状态中,这里为什么sleep是Thread的类方法而不是线程的方法,因为,能调用sleep的线程肯定是运行着的,而其他线程也是未运行的,所以调用其他线程的sleep是没有意义的。

6、wait、notify

  1. wait表示当前线程释放掉锁进入等待状态,所以调用waitnotify的前提是已经获取到对象的锁,如果没有获取到锁就使用wait那么会出异常信息。而进入等待状态的线程需要通过notify或者通过中断来唤醒进入到阻塞状态来等待锁的获取。这里对这种情况进行测试,使用notify唤醒一个等待状态的线程:
  1. class MyThreadd extends Thread{
  2. public MyThreadd(String name) {
  3. // TODO Auto-generated constructor stub
  4. super(name);
  5. }
  6. @Override
  7. public void run(){
  8. synchronized (this) {
  9. System.out.println(Thread.currentThread().getName()+" notify a thread");
  10. notify();
  11. }
  12. while(true);
  13. }

main中:

  1. MyThreadd t1 = new MyThreadd("t1");
  2. synchronized (t1) {
  3. System.out.println(Thread.currentThread().getName()+" start t1");
  4. t1.start();
  5. System.out.println(Thread.currentThread().getName()+" wait");
  6. t1.wait();
  7. System.out.println(Thread.currentThread().getName()+" waked up");
  8. }

这里可以看到,在main函数中,主线程将创建一个线程t1然后进入t1的锁的同步块中启动线程t1,然后调用wait进入等待状态,这个时候线程t1也进入到同步块中,调用notify后释放掉锁,可以看到主线程后续的东西继续被输出。当有多个线程调用了wait之后如果采用notify只会随机的唤醒其中的一个线程进入阻塞态,而采用notifyall会将所有的线程给唤醒。在线程运行结束后会调用notifyall将所有等待状态的线程唤醒。

7、join

  1. join的作用是让父线程等待子线程运行结束后在运行,通过查看源码可以知道:<br />![](https://cdn.nlark.com/yuque/0/2020/png/2332604/1597215957155-27ec35aa-4076-4f39-96b8-0748bb58bb37.png#align=left&display=inline&height=392&margin=%5Bobject%20Object%5D&originHeight=392&originWidth=617&size=0&status=done&style=none&width=617)<br />其实也是调用了先获取到子线程的锁然后调用wait方法来实现的,因为当子线程运行结束后会调用notifyall所以主线程会被唤醒并且再次获取到子线程的锁继续运行。
  1. class MyRuu extends Thread{
  2. public MyRuu(String name) {
  3. super(name);
  4. }
  5. @Override
  6. public void run() {
  7. System.out.println(Thread.currentThread().getName());
  8. //while(true);
  9. }
  10. }

main函数中:

  1. MyRuu myRuu = new MyRuu("t1");
  2. System.out.println(Thread.currentThread().getName()+" start t1");
  3. myRuu.start();
  4. System.out.println(Thread.currentThread().getName() +" join");
  5. myRuu.join();
  6. System.out.println(Thread.currentThread().getName() +" waked up");

运行结果:

  1. main start t1
  2. main join
  3. t1
  4. main waked up

可以看到,当主线程调用join后子线程开始运行,等子线程运行结束后主线程被唤醒。

8、yeild

  1. yeild的作用是线程让步,当前线调用yeild方法后线程从运行态进入到就绪态重新进入到CPU资源的竞争中。这里进行测试:
  1. class MyRun extends Thread{
  2. Object obj;
  3. public MyRun(String name,Object obj) {
  4. // TODO Auto-generated constructor stub
  5. super(name);
  6. this.obj = obj;
  7. }
  8. @Override
  9. public void run(){
  10. // synchronized (obj) {
  11. for (int i = 0; i < 10; i++) {
  12. System.out.println(Thread.currentThread().getName()+ " i="+i);
  13. if(i%2 == 0)
  14. Thread.yield();
  15. }
  16. // }
  17. }
  18. }

main函数中:

  1. Object obj = new Object();
  2. // TODO Auto-generated method stub
  3. MyRun t1 = new MyRun("t1",obj);
  4. MyRun t2 = new MyRun("t2",obj);
  5. t1.start();
  6. t2.start();

结果:

  1. t1 i=0
  2. t2 i=0
  3. t1 i=1
  4. t2 i=1
  5. t2 i=2
  6. t1 i=2
  7. t2 i=3
  8. t2 i=4
  9. t1 i=3
  10. t1 i=4
  11. t2 i=5
  12. t2 i=6
  13. t1 i=5
  14. t1 i=6
  15. t2 i=7
  16. t2 i=8
  17. t1 i=7
  18. t1 i=8
  19. t2 i=9
  20. t1 i=9

可以看到他们两个基本上是交替运行,而不用yeild让步的话大概率一个线程执行完成了另一个线程才会执行。

9、priority

  1. priority代表线程的优先级,在JVM中优先级高的线程不一定会先运行,只是先运行的概率会比低优先级的线程大。

10、中断

  1. 对于一个正常运行的线程中,中断基本是没有作用的,只是作为一个标志位来查询。而线程的其他几种状态下如sleepjoinwait状态下是可以被中断,并且通过中断来跳出当前状态的。
  1. class RunInt extends Thread{
  2. public void run() {
  3. while(!this.isInterrupted()){
  4. synchronized (this) {
  5. for (int i = 0; i < 10; i++) {
  6. System.out.println(Thread.currentThread().getName()+" i="+i);
  7. }
  8. try {
  9. Thread.sleep(3000);
  10. } catch (InterruptedException e) {
  11. // TODO Auto-generated catch block
  12. System.out.println(Thread.currentThread().getName()+" interrupted!");
  13. break;
  14. }
  15. }
  16. }
  17. System.out.println(Thread.currentThread().getName()+" dead");
  18. }
  19. }

main中:

  1. RunInt r1 = new RunInt();
  2. r1.start();
  3. Thread.yield();
  4. synchronized (r1) {
  5. System.out.println(Thread.currentThread().getName()+" intertupt r1");
  6. r1.interrupt();
  7. }

结果

  1. main intertupt r1
  2. Thread-0 i=0
  3. Thread-0 i=1
  4. Thread-0 i=2
  5. Thread-0 i=3
  6. Thread-0 i=4
  7. Thread-0 i=5
  8. Thread-0 i=6
  9. Thread-0 i=7
  10. Thread-0 i=8
  11. Thread-0 i=9
  12. Thread-0 interrupted!
  13. Thread-0 dead

可以看到,当主线程启动子线程后,子线程会进入到循环中并且进入到睡眠状态,然后主线程通过调用中断让子线程唤醒并且推出循环后死亡。

11、死锁

  1. 死锁指的是,两个线程互相等待对方释放资源导致卡死。例子:
  1. Thread t1 = new Thread(new Runnable() {
  2. @Override
  3. public void run() {
  4. // TODO Auto-generated method stub
  5. synchronized (A) {
  6. try {
  7. Thread.sleep(1000);
  8. } catch (InterruptedException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
  12. synchronized (B) {
  13. System.out.println("haha");
  14. }
  15. }
  16. }
  17. });
  18. Thread t2 = new Thread(new Runnable() {
  19. @Override
  20. public void run() {
  21. // TODO Auto-generated method stub
  22. synchronized (B) {
  23. synchronized (A) {
  24. System.out.println("xixi");
  25. }
  26. }
  27. }
  28. });
  29. t1.start();
  30. t2.start();

可以看到t1线程获得A的锁然后睡眠,然后t2线程获得B的锁然后再等待A释放锁,而线程t1睡眠完成后在等待t2释放B的锁,导致程序卡死。

12、生产者与消费者

  1. 生产者和消费者是多线程中一个很常见的应用场景,这里首先用一个共享变量实现生产者和消费者,接着再使用阻塞队列实现。首先实现第一种:<br />仓库代码:
  1. class Depot{
  2. private int capacity;
  3. private int size=0;
  4. public Depot(int c) {
  5. // TODO Auto-generated constructor stub
  6. this.capacity = c;
  7. }
  8. public synchronized void product(int count) throws InterruptedException{
  9. while(count>0){
  10. if(size >= capacity)
  11. wait();
  12. //真实生产数量
  13. int realcount = (capacity-size)>=count?count:(capacity-size);
  14. System.out.print(Thread.currentThread().getName()+"--本次想要生产:"+count+",本次实际生产:"+realcount);
  15. //下次生产数量
  16. count = count - realcount;
  17. //仓库剩余
  18. size += realcount;
  19. System.out.println(",下次想要生产:"+count+",仓库真实容量:"+size);
  20. notifyAll();
  21. }
  22. }
  23. public synchronized void comsume(int count) throws InterruptedException {
  24. while(count>0){
  25. if(size <= 0)
  26. wait();
  27. //真实消费数量
  28. int realcount = (size>=count)?count:size;
  29. System.out.print(Thread.currentThread().getName()+"--本次想要消费:"+count+",本次真实消费:"+realcount);
  30. //下次消费数量
  31. count = count - realcount;
  32. //仓库剩余
  33. size -= realcount;
  34. System.out.println("下次想要消费:"+count+",仓库剩余:"+size);
  35. notify();
  36. }
  37. }
  38. }

生产者代码:)

  1. class Producer {
  2. Depot depot;
  3. public Producer(Depot depot) {
  4. // TODO Auto-generated constructor stub
  5. this.depot = depot;
  6. }
  7. public void produce(final int count) {
  8. new Thread(){
  9. public void run() {
  10. try {
  11. depot.product(count);
  12. } catch (InterruptedException e) {
  13. // TODO Auto-generated catch block
  14. e.printStackTrace();
  15. }
  16. }
  17. }.start();
  18. }
  19. }

消费者代码:

  1. class Consumer{
  2. Depot depot;
  3. public Consumer(Depot depot) {
  4. // TODO Auto-generated constructor stub
  5. this.depot = depot;
  6. }
  7. public void consume(final int count) {
  8. new Thread(new Runnable() {
  9. @Override
  10. public void run() {
  11. // TODO Auto-generated method stub
  12. try {
  13. depot.comsume(count);
  14. } catch (InterruptedException e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. }
  19. }).start();
  20. }
  21. }

main中:

  1. Depot depot = new Depot(100);
  2. Producer producer = new Producer(depot);
  3. Consumer consumer = new Consumer(depot);
  4. producer.produce(60);
  5. producer.produce(50);
  6. producer.produce(30);
  7. consumer.consume(50);
  8. consumer.consume(110);
  9. producer.produce(40);

结果:

  1. Thread-0--本次想要生产:60,本次实际生产:60,下次想要生产:0,仓库真实容量:60
  2. Thread-1--本次想要生产:50,本次实际生产:40,下次想要生产:10,仓库真实容量:100
  3. Thread-4--本次想要消费:110,本次真实消费:100下次想要消费:10,仓库剩余:0
  4. Thread-1--本次想要生产:10,本次实际生产:10,下次想要生产:0,仓库真实容量:10
  5. Thread-4--本次想要消费:10,本次真实消费:10下次想要消费:0,仓库剩余:0
  6. Thread-5--本次想要生产:40,本次实际生产:40,下次想要生产:0,仓库真实容量:40
  7. Thread-2--本次想要生产:30,本次实际生产:30,下次想要生产:0,仓库真实容量:70
  8. Thread-3--本次想要消费:50,本次真实消费:50下次想要消费:0,仓库剩余:20

可以看到实现了生产者消费者模型。
第二种利用阻塞队列实现。直接利用阻塞队列当做仓库,生产者:

  1. class Pro1{
  2. private BlockingQueue<Integer> blockingQueue1;
  3. public Pro1(BlockingQueue<Integer> blockingQueue) {
  4. // TODO Auto-generated constructor stub
  5. this.blockingQueue1 = blockingQueue;
  6. }
  7. public void produce(final int count) {
  8. new Thread(new Runnable() {
  9. @Override
  10. public void run() {
  11. // TODO Auto-generated method stub
  12. for (int i = 0; i < count; i++) {
  13. try {
  14. Thread.sleep(100);
  15. blockingQueue1.put(100);
  16. System.out.println("生产者,仓库剩余容量"+blockingQueue1.size());
  17. } catch (InterruptedException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. }
  21. }
  22. }
  23. }).start();
  24. }
  25. }

消费者:

  1. class Con1{
  2. private BlockingQueue<Integer> blockingQueue;
  3. public Con1(BlockingQueue<Integer> blockingQueue) {
  4. // TODO Auto-generated constructor stub
  5. this.blockingQueue = blockingQueue;
  6. }
  7. public void consume(final int count) {
  8. new Thread(new Runnable() {
  9. @Override
  10. public void run() {
  11. // TODO Auto-generated method stub
  12. for (int i = 0; i < count; i++) {
  13. try {
  14. Thread.sleep(100);
  15. blockingQueue.take();
  16. System.out.println("消费者,本次仓库剩余:"+blockingQueue.size());
  17. } catch (InterruptedException e) {
  18. // TODO Auto-generated catch block
  19. e.printStackTrace();
  20. }
  21. }
  22. }
  23. }).start();
  24. }
  25. }

main函数:

  1. BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(5);
  2. Pro1 pro1 = new Pro1(blockingQueue);
  3. Con1 con1 = new Con1(blockingQueue);
  4. pro1.produce(10);
  5. con1.consume(7);

结果:

  1. 消费者,本次仓库剩余:0
  2. 生产者,仓库剩余容量0
  3. 生产者,仓库剩余容量1
  4. 消费者,本次仓库剩余:0
  5. 生产者,仓库剩余容量1
  6. 消费者,本次仓库剩余:0
  7. 生产者,仓库剩余容量0
  8. 消费者,本次仓库剩余:0
  9. 生产者,仓库剩余容量1
  10. 消费者,本次仓库剩余:0
  11. 生产者,仓库剩余容量1
  12. 消费者,本次仓库剩余:0
  13. 生产者,仓库剩余容量1
  14. 消费者,本次仓库剩余:0
  15. 生产者,仓库剩余容量1
  16. 生产者,仓库剩余容量2
  17. 生产者,仓库剩余容量3

这里阻塞队列的作用是,当容量不足的消费者进入等待队列,而当容量有剩余的时候消费者被唤醒,当容量已满的时候生产者进入等待队列,当容量被消费后生产者被唤醒。