JAVA多线程

39 阅读5分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

1.简介

  了解概念(并行并发,死锁)

  简单介绍:

  进程是操作系统调度和分配资源的最小单位,线程是CPU调度的最小单位。不同的进程之间是不共享内存的。进程之间的数据交换和通信的成本是很高。不同的线程是共享同一个进程的内存的。当然不同的线程也有自己独立的内存空间。对于方法区,堆中中的同一个对象的内存,线程之间是可以共享的,但是栈的局部变量永远是独立的。

2.创建线程的几种方法

  2.1继承Thread类

image

// 第一种开启子线程的方式,自定义线程类继承自Thread类

public class ThreadOne extends Thread {

   public ThreadOne(){

   }

   public ThreadOne(String name){//使用线程名的创建方法

       super(name);

   }

   @Override

   public void run() {

       // run方法中编写开启子线程后运行的代码

       for(int i = 1;i <= 100; i++){

           // getName()获取当前线程的线程名

           System.out.println(this.getName()+":"+i+"-------------------------------");

       }

   }

}

image

  2.2实现接口Runnable类

image

public class ThreadTwo implements Runnable{

   @Override

   public void run() {

       for (int i = 0; i < 100; i++) {

           try {

               Thread.currentThread().sleep(1000);

           } catch (InterruptedException e) {

               e.printStackTrace();

           }

           System.out.println(Thread.currentThread().getName()+"ThreadTwo ~~~~~~~~~~~~~~~~");

       }

   }

image

3.线程使用方法

  3.1继承类Thread类的使用方法

直接实例化,调用继承自Thread类的start()方法启动线程

image

public class Test00 {

   public static void main(String[] args) {

       Thread thread = new Thread();

       ThreadOne threadOne = new ThreadOne("小明");

       ThreadOne threadOne1 = new ThreadOne("Hock");

     

       threadOne.start();

       threadOne1.start();

   }

}

image

  3.2实现Runnable类的使用

实例化一个线程类,将Runnable的实现类传入,使用start()方法

image

public class Test01 {

   public static void main(String[] args) {

       ThreadTwo thread = new ThreadTwo();

       new Thread(thread).start();

       new Thread(thread).start();

       new Thread(thread).start();

   }

}

image

 

4.线程安全问题

  当线程访问同时访问一个资源时,会出现问题

image

package com.xm;

/**

  • @Author Mr.Alex

  • @Date 2021/11/15 18:43

  • @Version 1.0

*/

public class Test03 {

   public static void main(String[] args) {

       Ticks ticks = new Ticks();

       ThreadOne threadOne = new ThreadOne(ticks);

       ThreadOne threadOne1 = new ThreadOne(ticks);

       threadOne.start();

       threadOne1.start();

   }

}

class Ticks{

   private int tNums =100;//总计票数有100

   public void buyTicks(){

       if(tNums >0){

           System.out.println(Thread.currentThread().getName() + "买了一张票" + "还剩下" + --tNums + "张票");

       }

   }

   public int getNums() {

       return tNums;

   }

   public void settNums(int tNums) {

       this.tNums = tNums;

   }

}

class ThreadOne extends Thread{

   Ticks ticks;

   @Override

   public void run() {

       while (ticks.getNums()>0){

           ticks.buyTicks();

       }

   }

   public ThreadOne(Ticks ticks){

       this.ticks = ticks;

   }

}

image

image

 

(线程的调度看cpu的心情,结果可能有所差别)俩个不同的线程买到了同一张票。

解决问题:引入synchronized关键字,加入锁对象,使得同一个资源只有一个线程访问,当一个线程结束访问时,另一个线程才能访问

使用锁方法时,默认锁对象:

(1)静态方法:锁对象是当前类的Class对象

(2)非静态方式:this

image

package com.xm;

/**

  • @Author Mr.Alex

  • @Date 2021/11/15 18:43

  • @Version 1.0

*/

public class Test03 {

   public static void main(String[] args) {

       Ticks ticks = new Ticks();

       ThreadOne threadOne = new ThreadOne(ticks);

       ThreadOne threadOne1 = new ThreadOne(ticks);

       threadOne.start();

       threadOne1.start();

   }

}

class Ticks{

   private int tNums =100;//总计票数有100

   public synchronized void buyTicks(){

       if(tNums >0) {

           System.out.println(Thread.currentThread().getName() + "买了一张票" + "还剩下" + --tNums + "张票");

           try {

               Thread.sleep(10);

           } catch (InterruptedException e) {

               e.printStackTrace();

           }

       }

       else {

           System.out.println(Thread.currentThread().getName() + "没买到票,票卖完了----------");

       }

   }

   public int getNums() {

       return tNums;

   }

   public void settNums(int tNums) {

       this.tNums = tNums;

   }

}

class ThreadOne extends Thread{

   Ticks ticks;

   @Override

   public void run() {

       while (ticks.getNums()>=1){

           ticks.buyTicks();

       }

   }

   public ThreadOne(Ticks ticks){

       this.ticks = ticks;

   }

}

image

 

synchronized关键字还可以修饰代码块,注意

(1)必须是对象,不能是基本数据类型

(2)这个锁对象,必须保证多个线程之间使用的是同一个

synchronized(锁对象){

   需要同步的代码

}

5.线程通信

生产者和消费者问题

解决方法:引入下面方法,通知线程是工作还是休息

image

java.lang.Object类的方式:

(1)wait():等待

(2)notify()/notifyAll():唤醒

它们都必须由“锁/对象监视器”来调用,否则就会报错。

image

 

设定菜品初始值为一百,菜品为一百时厨师不做菜,菜品等于0时服务员不上菜,其他时候厨师服务员都工作。

菜品类Dish:

image

package com.alex;

/**

  • @Author Mr.Alex

  • @Date 2021/11/15 11:24

  • @Version 1.0

*/

public class Dish {

   private int dishNums = 100;

   public synchronized void add(){

       while (dishNums>=100){

           System.out.println("菜够了,厨师" + Thread.currentThread().getName() + "不做菜了");

           try {

               this.wait();

           } catch (InterruptedException e) {

               e.printStackTrace();

           }

       }

       try{

           Thread.sleep(100);

       }catch (InterruptedException e){

           e.printStackTrace();

       }

       System.out.println("厨师" + Thread.currentThread().getName() + "做了一道菜" + "还剩下" + ++dishNums + "道菜");

       this.notifyAll();

   }

   public synchronized void sub(){

       while (dishNums <= 0){

           System.out.println("菜不够了,服务员" + Thread.currentThread().getName() + "不送菜了");

           try {

               this.wait();

           }catch (InterruptedException e){

               e.printStackTrace();

           }

       }

       try{

           Thread.sleep(50);

       }catch (InterruptedException e){

           e.printStackTrace();

       }

       System.out.println("服务员" + Thread.currentThread().getName() + "送了一道菜" + "还剩下" + --dishNums + "道菜");

       this.notifyAll();

   }

}

image

厨师类Cooker

image

package com.alex;

/**

  • @Author Mr.Alex

  • @Date 2021/11/15 11:42

  • @Version 1.0

*/

public class Cooker implements Runnable{

   private Dish dish;

   public Cooker(Dish dish) {

       this.dish = dish;

   }

   @Override

   public void run() {

       while (true) {

           dish.add();

       }

   }

}

image

服务员Attendant:

image

package com.alex;

/**

  • @Author Mr.Alex

  • @Date 2021/11/15 11:42

  • @Version 1.0

*/

public class Cooker implements Runnable{

   private Dish dish;

   public Cooker(Dish dish) {

       this.dish = dish;

   }

   @Override

   public void run() {

       while (true) {

           dish.add();

       }

   }

}

image

测试类Test02:(三个厨师,三个服务员)

image

package com.xm;

import com.alex.Attendant;

import com.alex.Cooker;

import com.alex.Dish;

/**

  • @Author Mr.Alex

  • @Date 2021/11/15 11:45

  • @Version 1.0

*/

public class Test02 {

   public static void main(String[] args) {

       Dish dish = new Dish();

       Cooker cooker = new Cooker(dish);

       Attendant attendant = new Attendant(dish);

       new Thread(cooker).start();

       new Thread(cooker).start();

       new Thread(cooker).start();

       new Thread(attendant).start();

       new Thread(attendant).start();

       new Thread(attendant).start();

   }

}

image

6.死锁

当俩个或多个线程互相持有对方想要的锁时会出现死锁。

image

package com.xm;

/**

  • @Author Mr.Alex

  • @Date 2021/11/15 19:32

  • @Version 1.0

*/

public class Test04 {

   public static void main(String[] args) {

       A a = new A();

       B b = new B();

       ThreadTest threadTest = new ThreadTest(a);

       ThreadTest threadTest1 = new ThreadTest(b);

       threadTest.start();

       threadTest1.start();

   }

}

class ThreadTest extends Thread{

   Object obj;

   public ThreadTest(Object obj) {

       this.obj = obj;

   }

   @Override

   public void run() {

       if(obj instanceof A){

           obj = (A) obj;

           synchronized ("猪脚饭") {

               ((A) obj).get();

               synchronized ("北京烤鸭") {

                   ((A) obj).eat();

               }

           }

       }

       else if(obj instanceof B){

           obj = (B) obj;

           synchronized ("北京烤鸭") {

               ((B) obj).get();

               synchronized ("猪脚饭") {

                   ((B) obj).eat();

               }

           }

       }

       else obj = null;

   }

}

class A{

   public void get(){

       System.out.println("我想要猪脚饭");

   }

   public void eat(){

       System.out.println("吃到了猪脚饭嘻嘻~~");

   }

}

class B{

   public void get(){

       System.out.println("我想要北京烤鸭");

   }

   public void eat(){

       System.out.println("吃到了北京烤鸭嘻嘻~~");

   }

}

image

想吃猪脚饭的,拿了北京烤鸭的锁

想吃北京烤鸭的,拿了猪脚饭的锁

互相拿了对面的资源,发生死锁

image

 

注意释放锁的操作

image

会释放锁:

1、线程死亡

2、wait()

不会释放锁:

1、sleep()

2、yield()

image

守护线程(了解,这里简单介绍一下,具体请查阅相关资料)

  守护线程是在后台运行的,它的任务是为其他线程提供服务的,这种线程被称为“守护线程”。JVM的垃圾回收线程就是典型的守护线程。

守护线程有个特点,就是如果所有非守护线程都死亡,那么守护线程自动死亡。

调用setDaemon(true)方法可将指定线程设置为守护线程。必须在线程启动之前设置,否则会报IllegalThreadStateException异常。

调用isDaemon()可以判断线程是否是守护线程。