【JavaSE】线程,同步与死锁,Thread类 ,Runnable接口 ,synchronized (),wait(),经典案例:生产者与消费者

一、Java中多线程的创建和使用

Thread类

Java语言的JVM允许程序运行多个线程,它通过java.lang.Thread类来实现。

Thread类的特性:
      每个线程都是通过某个特定Thread对象的run()方法来完成操作的,经常把run()方法的主体称为线程体
      通过该Thread对象的**start()**方法来调用这个线程,启动线程

Thread类构造方法:

Thread():创建新的Thread对象
Thread(String threadname):创建线程并指定线程实例名
Thread(Runnable target):指定创建线程的目标对象,它实现了Runnable接口中的run方法
Thread(Runnable target, String name):创建新的Thread对象

继承Thread类创建线程

  1. 定义子类继承Thread类。
  2. 子类中重写Thread类中的run方法。
  3. 创建Thread子类对象,即创建了线程对象。
  4. 调用线程对象start方法:启动线程,调用run方法。
public class TestThread extends Thread{
    /**
     * 继承Thread的方式实现多线程
     * @author lby
     *
     */

    @Override
    public void run() {
        System.out.println("多线程运行的代码");
        for(int i = 0; i < 5; i++){

            System.out.println("这是多线程的逻辑代码:" + i);
        }
    }
}

实现Runnable接口(一般用这个)

  1. 定义子类,实现Runnable接口。
  2. 子类中重写Runnable接口中的run方法。
  3. 通过Thread类含参构造器创建线程对象。
  4. 将Runnable接口的子类对象作为实际参数传递给Thread类的构造方法中。
  5. 调用Thread类的start方法:开启线程,调用 Runnable子类接口的run方法。
public class TestRunnable implements Runnable {
    @Override
    /**
     * 通过实现Runnable接口方式实现多线程
     * @author lby
     *
     */

    public void run() {
        int count = 0;
        //Thread.currentThread().getName()获取线程名称
            System.out.println(Thread.currentThread().getName() + ":Runnable多线程运行的代码");
            for (int i = 0; i < 5; i++) {
                count++;
                System.out.println(Thread.currentThread().getName() + ":这是Runnable多线程的逻辑代码:" + count);
            }

    }
}

public class text {
    public static void main(String[] args) {
 //       Thread t0 = new TestThread();//继承Thread类的线程
//		t0.start();//启动线程,开始运行run方法中的代码


        Thread t1 = new Thread(new TestRunnable());//传入一个Runnable的实例
        //t1.start();

        Thread t2 = new Thread(new TestRunnable() , "t-1");
        t2.start();
        Thread t3 = new Thread(new TestRunnable() , "t-2");
        t3.start();


        System.out.println("---------------");
        System.out.println("---------------");
        System.out.println("---------------");
    }
}

继承方式和实现方式的联系与区别

【区别】
继承Thread: 线程代码存放Thread子类run方法中。重写run方法
实现Runnable:线程代码存在接口的子类的run方法。实现run方法

【实现接口方式的好处】
1)避免了单继承的局限性
2)多个线程可以共享同一个接口实现类的对象,非常适合多个相同线程来处理同一份资源。
一般使用实现接口方式来实现多线程

共享同一个接口实现类:

Runnable run =  new TestRunnable();
        Thread t4 = new Thread(run , "t-1");
        t4.start();
        Thread t5 = new Thread(run , "t-2");
        t5.start();
int count = 0;
    public void run() {
        //Thread.currentThread().getName()获取线程名称
            System.out.println(Thread.currentThread().getName() + ":Runnable多线程运行的代码");
            for (int i = 0; i < 5; i++) {
                count++;
                System.out.println(Thread.currentThread().getName() + ":这是Runnable多线程的逻辑代码:" + count);
            }

    }

输出结果:

t-2:Runnable多线程运行的代码
t-1:Runnable多线程运行的代码
t-1:这是Runnable多线程的逻辑代码:2
t-1:这是Runnable多线程的逻辑代码:3
t-1:这是Runnable多线程的逻辑代码:4
t-1:这是Runnable多线程的逻辑代码:5
t-1:这是Runnable多线程的逻辑代码:6
t-2:这是Runnable多线程的逻辑代码:1
t-2:这是Runnable多线程的逻辑代码:7
t-2:这是Runnable多线程的逻辑代码:8
t-2:这是Runnable多线程的逻辑代码:9
t-2:这是Runnable多线程的逻辑代码:10
共享了TestRunnable里的count

二、Thread的相关方法

void start(): 启动线程,并执行对象的run()方法
run(): 线程在被调度时执行的操作
String getName(): 返回线程的名称
void setName(String name): 设置该线程名称
static currentThread(): 返回当前线程

线程的优先级控制
MAX_PRIORITY(10); 最高优先级(10)
MIN _PRIORITY (1); 最低优先级(1)
NORM_PRIORITY (5);默认优先级(5)
涉及的方法:
getPriority() : 返回线程优先值
setPriority(int newPriority) : 改变线程的优先级
线程创建时继承父线程的优先级

static void yield():线程让步
暂停当前正在执行的线程,把执行机会让给优先级相同或更高的线程
若队列中没有同优先级的线程,忽略此方法
join() :当某个程序执行流中调用其他线程的 join() 方法时,调用线程将被阻塞,直到 join() 方法加入的 join 线程执行完为止
低优先级的线程也可以获得执行
static void sleep(long millis):(指定时间:毫秒)
令当前活动线程在指定时间段内放弃对CPU控制,使其他线程有机会被执行,时间到后重排队。抛出InterruptedException异常
stop(): 强制线程生命期结束
boolean isAlive(): 返回boolean,判断线程是否还活着

public class text1 {
    public static void main(String[] args) {

        Textrun run0 = new Textrun();
        Textrun run1 = new Textrun();

        Thread t0 = new Thread(run0);
        t0.start();
        Thread t1 = new Thread(run1);
        t1.start();

        //t0.setName("线程01");//设置名称

        //t0.setPriority(1);//设置线程的优先级
		//t1.setPriority(10);//设置线程的优先级

        //创建线程时不指定名称会输出默认名称
        // System.out.println(t0.getName());
        // System.out.println(t1.getName());

        /**
         * 线程的优先级,就是哪个线程有较大个概率被执行
         * 优先级是用数组1-10表示,数字越大优先级越高,如果没有设置默认优先级是5
         */

		// System.out.println("t0的优先级:" + t0.getPriority());//获取线程的优先级
		// System.out.println("t1的优先级:" + t1.getPriority());//获取线程的优先级

        System.out.println("---------------");
        System.out.println("---------------");
        System.out.println(t1.isAlive());//判断当前的线程是否存活

        t1.stop();//强制线程生命期结束,强制停止此线程

        try {
            t0.join();//相当于在这块把t0的run的代码插入到这个位置执行
            /**
             * 专业的说法
             * 就是阻塞当前的main方法,先不执行System.out.println("---------------3");代码
             * 先执行join进来的线程的代码
             * join的线程执行完毕之后继续执行之前main方法阻塞的代码System.out.println("---------------3");
             */
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("---------------");
        System.out.println(t1.isAlive());
    }
}


class Textrun implements Runnable{

    int count = 0;
    @Override
    public void run() {
        //Thread.currentThread().getName()获取线程名称
        System.out.println(Thread.currentThread().getName() + ":Runnable多线程运行的代码");
        for (int i = 0; i < 5; i++) {

            // if(i % 2 == 0){
			// 	Thread.yield();//线程让步
			// }

            try {
                Thread.sleep(1000);//当前线程睡眠1000毫秒
//				//相当于当前的这个循环每隔1000毫秒执行一次循环
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            count++;
            System.out.println(Thread.currentThread().getName() + ":这是Runnable多线程的逻辑代码:" + count);
        }
    }
}

三、线程的生命周期

JDK中用Thread.State枚举表示了线程的几种状态
要想实现多线程,必须在主线程中创建新的线程对象。Java语言使用Thread类及其子类的对象来表示线程,在它的一个完整的生命周期中通常要经历如下的五种状态:

  • 新建: 当一个Thread类或其子类的对象被声明并创建时,新生的线程对象处于新建状态
  • 就绪:处于新建状态的线程被start()后,将进入线程队列等待CPU时间片,此时它已具备了运行的条件
  • 运行:当就绪的线程被调度并获得处理器资源时,便进入运行状态, run()方法定义了线程的操作和功能
  • 阻塞:在某种特殊情况下,被人为挂起或执行输入输出操作时,让出 CPU 并临时中止自己的执行,进入阻塞状态
  • 死亡:线程完成了它的全部工作或线程被提前强制性地中止

在这里插入图片描述

四、线程的同步Synchronized的使用方法

问题的提出
      多个线程执行的不确定性引起执行结果的不稳定
      多个线程对账本的共享,会造成操作的不完整性,会破坏数据。

在这里插入图片描述

Java对于多线程的安全问题提供了专业的解决方式:
      同步机制

  1. ynchronized还可以放在方法声明中,表示整个方法
    为同步方法。
    例如:
          public synchronized void show (String name){
    ….
    }
  2. synchronized (对象){
          // 需要被同步的代码;
    }

1.不加同步锁效果

public class text2 {
    public static void main(String[] args) {
        //定义用户对象
        Accunt a = new Accunt();

        //多线程对象
        User u_weixin = new User(a,2000);
        User u_zhifubao = new User(a,2000);

        Thread t0 = new Thread(u_weixin,"微信");
        Thread t1 = new Thread(u_zhifubao,"支付宝");

        t0.start();
        t1.start();
    }
}


class Accunt{
    public static int MONEY = 3000;//全局变量,所有的操作共享这个变量
    public void draw(int m){
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }
}

class User implements Runnable{
    Accunt accunt;
    int money;

    public User(Accunt accunt,int money){
        this.accunt = accunt;
        this.money = money;
    }
    @Override
    public void run() {
        accunt.draw(money);
    }
}
//
微信操作,余额原有金额:3000
支付宝操作,余额原有金额:3000
支付宝操作,提取金额:2000
微信操作,提取金额:2000
提款后余额为:1000
提款后余额为:-1000

2.直接在方法上加上synchronized关键字

  • 可以直接在方法上加上synchronized关键字
  • 在普通方法上加同步锁synchronized,锁的是整个对象,不是某一个方法
  • 不同的对象就是不同的锁,普通方法加synchronized,线程使用不同的此方法的对象,还有共享资源的问题

//可以直接在方法上加上synchronized关键字
class  Accunt{
    public static int MONEY = 3000;
    public synchronized void draw(int m){//这里加上synchronized
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }
}
//
微信操作,余额原有金额:3000
微信操作,提取金额:2000
提款后余额为:1000
支付宝操作,账户余额不足:1000

3.在普通方法上加同步锁synchronized,锁的是整个对象,不是某一个方法

在普通方法上加同步锁synchronized,锁的是整个对象,不是某一个方法

//在普通方法上加同步锁synchronized,锁的是整个对象,不是某一个方法
public class text2 {
    public static void main(String[] args) {
        //定义用户对象
        Accunt a = new Accunt();

        //多线程对象
        User u_weixin = new User(a,2000);
        User u_zhifubao = new User(a,2000);

        Thread t0 = new Thread(u_weixin,"微信");
        Thread t1 = new Thread(u_zhifubao,"支付宝");

        t0.start();
        t1.start();
    }
}


class  Accunt{
    public static int MONEY = 3000;
    public synchronized void draw(int m){
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }

    public synchronized void draw1(int m){
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }
}

class  User implements Runnable{
    Accunt accunt;
    int money;

    public User(Accunt accunt,int money){
        this.accunt = accunt;
        this.money = money;
    }
    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("微信")){
            accunt.draw1(money);
        }else
        accunt.draw(money);
    }
}
//
微信操作,余额原有金额:3000
微信操作,提取金额:2000
提款后余额为:1000
支付宝操作,账户余额不足:1000

分析:
这里微信和支付宝使用的方法是不一样的,一个是draw一个是draw1,但是也达到了同步锁的效果,因此证明了,在普通方法上加同步锁synchronized,锁的是整个对象,不是某一个方法

4.不同的对象就是不同的锁,普通方法加synchronized,线程使用不同的此方法的对象,还有共享资源的问题

//不同的对象就是不同的锁,普通方法加synchronized,线程使用不同的此方法的对象,还有共享资源的问题

Accunt a = new Accunt();
        Accunt a1 = new Accunt();
User u_weixin = new User(a,2000);
        User u_zhifubao = new User(a1,2000);

public void run() {
        if (Thread.currentThread().getName().equals("微信")){
            accunt.draw1(money);
        }else
        accunt.draw(money);
    }
//
微信操作,余额原有金额:3000
支付宝操作,余额原有金额:3000
支付宝操作,提取金额:2000
微信操作,提取金额:2000
提款后余额为:-1000
提款后余额为:1000

分析:
这里微信调用的是a的draw方法,支付宝调用的是a1的draw1的方法,但没有达到同步锁的效果,整明了不同的对象就是不同的锁,普通方法加synchronized,线程使用不同的此方法的对象,还有共享资源的问题

5.静态的方法加synchronized,对于所有的对象都是使用同一个一个锁

// 静态的方法加synchronized,对于所有的对象都是使用同一个一个锁
public class text2 {
    public static void main(String[] args) {
        //定义用户对象
        Accunt a = new Accunt();
        Accunt a1 = new Accunt();

        User u_weixin = new User(a,2000);
        User u_zhifubao = new User(a1,2000);

        Thread t0 = new Thread(u_weixin,"微信");
        Thread t1 = new Thread(u_zhifubao,"支付宝");

        t0.start();
        t1.start();
    }
}


class  Accunt{
    public static int MONEY = 3000;
    public static synchronized void draw2(int m){
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }
}

class  User implements Runnable{
    Accunt accunt;
    int money;

    public User(Accunt accunt,int money){
        this.accunt = accunt;
        this.money = money;
    }
    @Override
    public void run() {
        accunt.draw2(money);
    }
}
//
微信操作,余额原有金额:3000
微信操作,提取金额:2000
提款后余额为:1000
支付宝操作,账户余额不足:1000

分析:
这里的draw2是静态方法,就算创建对象的时候是分开创建的一个是a一个是a1,但是也同样可以达到同步锁效果,证明了 静态的方法加synchronized,对于所有的对象都是使用同一个一个锁。

6.对代码块加入同步锁

public class text2 {
    public static void main(String[] args) {
        //定义用户对象
        Accunt a = new Accunt();
        Accunt a1 = new Accunt();

        //多线程对象
        User u_weixin = new User(a,2000);
        User u_zhifubao = new User(a,2000);
        
        Thread t0 = new Thread(u_weixin,"微信");
        Thread t1 = new Thread(u_zhifubao,"支付宝");

        t0.start();
        t1.start();
    }
}


class  Accunt{
    public static int MONEY = 3000;
    public synchronized void draw(int m){
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }

    /**
     * 对代码块加入同步锁
     * 代码块synchronized(this),所有当前的对象的synchronized(this)同步的的代码都是使用同一个锁
     * @param m
     */
    public void draw3(int m) {
        String name = Thread.currentThread().getName();
        synchronized (this) {//表示当前的对象的代码块被加了synchronized同步锁
            if (MONEY < m) {
                System.out.println(name + "操作,账户余额不足:" + MONEY);
            } else {
                System.out.println(name + "操作,余额原有金额:" + MONEY);
                System.out.println(name + "操作,提取金额:" + m);

                MONEY = MONEY - m;
                System.out.println("提款后余额为:" + MONEY);
            }
        }
    }
}

class  User implements Runnable{
    Accunt accunt;
    int money;

    public User(Accunt accunt,int money){
        this.accunt = accunt;
        this.money = money;
    }
    @Override
    public void run() {
     
    accunt.draw3(money);
    }
}
//
微信操作,余额原有金额:3000
微信操作,提取金额:2000
提款后余额为:1000
支付宝操作,账户余额不足:1000

调用同一个对象也能达到同步锁的效果

7.synchronized (this),this的作用

用this锁代码块是代表当前的对象,如果在其他方法中也有synchronized(this)的代码块使用的都是同一个同步锁,如果两次this不是同一个对象,那也锁不住。

public class text2 {
    public static void main(String[] args) {
        //定义用户对象
        Accunt a = new Accunt();
        Accunt a1 = new Accunt();

        //多线程对象
        // User u_weixin = new User(a,2000);
        // User u_zhifubao = new User(a,2000);

        User u_weixin = new User(a,2000);
        User u_zhifubao = new User(a1,2000);

        Thread t0 = new Thread(u_weixin,"微信");
        Thread t1 = new Thread(u_zhifubao,"支付宝");

        t0.start();
        t1.start();
    }
}

class  Accunt{
    public static int MONEY = 3000;
    public synchronized void draw(int m){
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }

   

    /**
     * 对代码块加入同步锁
     * 代码块synchronized(this),所有当前的对象的synchronized(this)同步的的代码都是使用同一个锁
     * @param m
     */
    public void draw3(int m) {
        String name = Thread.currentThread().getName();
        synchronized (this) {//表示当前的对象的代码块被加了synchronized同步锁
            //用this锁代码块是代表当前的对象,如果在其他方法中也有synchronized(this)的代码块使用的都是同一个同步锁
            if (MONEY < m) {
                System.out.println(name + "操作,账户余额不足:" + MONEY);
            } else {
                System.out.println(name + "操作,余额原有金额:" + MONEY);
                System.out.println(name + "操作,提取金额:" + m);

                MONEY = MONEY - m;
                System.out.println("提款后余额为:" + MONEY);
            }
        }
    }

    public void draw4(int m) {
        String name = Thread.currentThread().getName();
        synchronized (this) {//表示当前的对象的代码块被加了synchronized同步锁
            //用this锁代码块是代表当前的对象,如果在其他方法中也有synchronized(this)的代码块使用的都是同一个同步锁
            if (MONEY < m) {
                System.out.println(name + "操作,账户余额不足:" + MONEY);
            } else {
                System.out.println(name + "操作,余额原有金额:" + MONEY);
                System.out.println(name + "操作,提取金额:" + m);

                MONEY = MONEY - m;
                System.out.println("提款后余额为:" + MONEY);
            }
        }
    }
}

class  User implements Runnable{
    Accunt accunt;
    int money;

    public User(Accunt accunt,int money){
        this.accunt = accunt;
        this.money = money;
    }
    @Override
    public void run() {
    //     if (Thread.currentThread().getName().equals("微信")){
    //         accunt.draw3(money);
    //     }else
    //     accunt.draw4(money);
     
    accunt.draw3(money);
    }
}

分析:

  1. 微信支付宝创建同一个对象,分别使用draw3和draw4,运行结果达到了同步锁的效果
  2. 微信支付宝分享创建两个对象a和a1,都使用draw3方法,但是并没有锁住
    总结:用this锁代码块是代表当前的对象,如果在其他方法中也有synchronized(this)的代码块使用的都是同一个同步锁,如果两次this不是同一个对象,那也锁不住

8.synchronized修饰代码块,想要根据不同的对象有不同的锁

public void drawing5(int m,Acount a){
		synchronized(a){//表示通过方法的参数传递进来的对象的代码块被加了synchronized同步锁
			//不同的对象就有不同的同步锁
			String name = Thread.currentThread().getName();
			
			
			if(money < m){
				System.out.println(name + "操作,账户金额不足:" + money);
			}else{
				System.out.println(name + "操作,账户原有金额:" + money);
				System.out.println(name + "操作,取款金额:" + m);
				
				System.out.println(name + "操作,取款操作:原金额" + money + " - " + "取款金额" + m);
				money = money - m;
				System.out.println(name + "操作,取款后的余额:" + money);
			}
	}
} 

9.总结

如果针对对象加同步锁就加在方法上。
如果针对某一段代码需要加同步锁,,那就直接在代码块上加同步锁

五、线程的通信

wait() 与 notify() 和 notifyAll()
wait():令当前线程挂起并放弃CPU、同步资源,使别的线程可访问并修改共享资源,而当前线程排队等候再次对资源的访问
notify():唤醒正在排队等待同步资源的线程中优先级最高者结束等待
notifyAll ():唤醒正在排队等待资源的所有线程结束等待.
Java.lang.Object提供的这三个方法只有在synchronized方法或synchronized代码块中才能使用,否则会报java.lang.IllegalMonitorStateException异常

wait() 方法
在当前线程中调用方法: 对象名.wait()
使当前线程进入等待(某对象)状态 ,直到另一线程对该对象发出 notify (或notifyAll) 为止。
调用方法的必要条件:当前线程必须具有对该对象的监控权(加锁)
调用此方法后,当前线程将释放对象监控权 ,然后进入等待
在当前线程被notify后,要重新获得监控权,然后从断点处继续代码的执行。

notify()/notifyAll()
在当前线程中调用方法: 对象名.notify()
功能:唤醒等待该对象监控权的一个线程。
调用方法的必要条件:当前线程必须具有对该对象的监控权(加锁)

public class text2 {
    public static void main(String[] args) {
        //定义用户对象
        Accunt a = new Accunt();
        Accunt a1 = new Accunt();

        //多线程对象
        User u_weixin = new User(a,2000);
        User u_zhifubao = new User(a,2000);

        Thread t0 = new Thread(u_weixin,"微信");
        Thread t1 = new Thread(u_zhifubao,"支付宝");

        t0.start();
        t1.start();
    }
}


class  Accunt{
    public static int MONEY = 3000;
    public synchronized void draw(int m){
        String name = Thread.currentThread().getName();

        if (MONEY < m){
            System.out.println(name + "操作,账户余额不足:" + MONEY);
        }else {
            System.out.println(name + "操作,余额原有金额:" + MONEY);
            System.out.println(name + "操作,提取金额:" + m);

            MONEY = MONEY - m;
            System.out.println("提款后余额为:" + MONEY);
        }
    }

    public void draw5(int m ,Accunt a) {
        String name = Thread.currentThread().getName();
        synchronized (a) {//表示通过方法的参数传递进来的对象的代码块被加了synchronized同步锁
			//不同的对象就有不同的同步锁

            //如果是微信操作的,先不执行,等支付宝操作,支付宝操作完,微信再继续操作
            if(name.equals("微信")){
                try {
                    this.wait();//当前的线程进入等待的阻塞状态
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            if (MONEY < m) {
                System.out.println(name + "操作,账户余额不足:" + MONEY);
            } else {
                System.out.println(name + "操作,余额原有金额:" + MONEY);
                System.out.println(name + "操作,提取金额:" + m);

                MONEY = MONEY - m;
                System.out.println("提款后余额为:" + MONEY);
            }

            if(name.equals("支付宝")){
                try {
                    a.notify();//唤醒当前优先级最高的线程,进入就绪状态
//					a.notifyAll();//唤醒当前所有的线程,进入就绪状态
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

class  User implements Runnable{
    Accunt accunt;
    int money;

    public User(Accunt accunt,int money){
        this.accunt = accunt;
        this.money = money;
    }
    @Override
    public void run() {
 
    accunt.draw5(money , accunt);
    }
}
//
支付宝操作,余额原有金额:3000
支付宝操作,提取金额:2000
提款后余额为:1000
微信操作,账户余额不足:1000

synchronized (a) {//表示通过方法的参数传递进来的对象的代码块被加了synchronized同步锁
//不同的对象就有不同的同步锁
执行完支付宝在执行微信

六、经典例题:生产者/消费者问题

生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下,如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,如果店中有产品了再通知消费者来取走产品。

这里可能出现两个问题:
      生产者比消费者快时,消费者会漏掉一些数据没有取到。
      消费者比生产者快时,消费者会取相同的数据。

生产时不允许消费,消费时不允许生产

package day15;

/**
 * 生产者与消费者
 * @author lby
 *
 */
public class Test3 {
	public static void main(String[] args) {
		Clerk c = new Clerk();
		//消费时不生产,生产时不消费
		
		//生产者
		new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (c) {
					while(true){//无限循环代表无限的生产次数
						if(c.productNum == 0){//产品数为0,开始生产
							System.out.println("产品数为0,开始生产");
							while(c.productNum < 4){
								c.productNum++;//增加产品
								System.out.println("库存:" + c.productNum);
							}
							System.out.println("产品数为" + c.productNum + ",结束生产");
							
							c.notify();//唤醒消费者线程
						}else{
							try {
								c.wait();//生产者线程等待
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}, "生产者").start();
		
		//消费者
		new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (c) {
					while(true){//无限循环代表无限的消费次数
						if(c.productNum == 4){//产品数为4,开始消费
							System.out.println("产品数为4,开始消费");
							while(c.productNum > 0){
								c.productNum--;//消费产品
								System.out.println("库存:" + c.productNum);
							}
							System.out.println("产品数为" + c.productNum + ",结束消费");
							
							c.notify();//唤醒生产者线程
						}else{
							try {
								c.wait();//消费者线程等待
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		}, "消费者").start();
		
	}
}


class Clerk{
	public static int productNum = 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值