Java从零开始 基础(五)线程同步和通信

时间:2021-08-18 10:21:21   收藏:0   阅读:16

线程同步

不安全试例

没有加锁,线程不安全,会出现同一张票卖给两个不同的人

package com.syn;

public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "Jack").start();
        new Thread(buyTicket, "Tom").start();
        new Thread(buyTicket, "yellow cow").start();
    }
}

class BuyTicket implements Runnable {
    boolean flag = true;  // 停止线程标志位
    int ticket_nums = 0;

    @Override
    public void run() {
        while (flag) {
            try {
                buy();  // 买票
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void buy() throws InterruptedException {
        if (ticket_nums >= 10) {
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "拿到第 " + ticket_nums++ + " 张票");
    }
}
/*
  yellow cow拿到第 1 张票
  Jack拿到第 3 张票
  Tom拿到第 2 张票
  Tom拿到第 4 张票
  yellow cow拿到第 5 张票
  Jack拿到第 4 张票
  Tom拿到第 6 张票
  yellow cow拿到第 6 张票
  Jack拿到第 7 张票
  Tom拿到第 8 张票
  Jack拿到第 9 张票
  yellow cow拿到第 8 张票
*/

Synchronized 线程锁

死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,二导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。

产生死锁的四个必要条件:

package com.syn;

// 死锁:多个线程互相抢占对方需要的资源,形成僵持
public class DeadLock {
    public static void main(String[] args) {
        Makeup m1 = new Makeup(0,"Tom");
        Makeup m2 = new Makeup(1,"Jack");

        m1.start();
        m2.start();
    }
}

// 口红
class Lipstick{}

// 镜子
class Mirror{}

class Makeup extends Thread{
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;
    String girlName;

    Makeup(int choice, String girlName){
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        // 化妆
        try {
            makeUp();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 化妆,互相持有对方的锁,就是需要拿到对方需要的资源
    private void makeUp() throws InterruptedException {
        if (choice==0){
            synchronized (lipstick){
                System.out.println(this.girlName+" 获得口红的锁");
                Thread.sleep(100);

                synchronized (mirror){  // 100毫秒后想获得镜子
                    System.out.println(this.girlName+" 获得镜子的锁");
                }
            }
        }else {
            synchronized (mirror){
                System.out.println(this.girlName+" 获得镜子的锁");
                Thread.sleep(200);

                synchronized (lipstick){
                    System.out.println(this.girlName+" 获得口红的锁");
                }
            }
        }
    }
}

Lock 锁

synchronized 与 Lock 的对比

package com.syn;
import java.util.concurrent.locks.ReentrantLock;

public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }
}

class TestLock2 implements Runnable {
    int ticket_num = 1;
    // 定义Lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();  // 加锁
                if (ticket_num <= 10) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticket_num++);
                } else {
                    break;
                }
            } finally {
                lock.unlock();  // 解锁
            }

        }
    }
}

线程通信

生产者消费者模式

是一个问题,并不是23中设计模式之一

应用场景:

问题:

方法:

解决方式1:并发协作模型“生产者/ 消费者模式”->管程法

解决方式2:并发协作模型“生产者/消费者模式”…>信号灯法

管程法

package com.syn;

// 生产者消费者模型:利用缓冲区解决:管程法
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Producer(container).start();
        new Consumer(container).start();
    }
}

// 生产者
class Producer extends Thread {
    SynContainer container;
    public Producer(SynContainer container) {
        this.container = container;
    }

    // 生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了" + i + " 只鸡");
            try {
                container.push(new Chicken(i));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

// 消费者
class Consumer extends Thread {
    SynContainer container;
    public Consumer(SynContainer container) {
        this.container = container;
    }
    // 消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                System.out.println("消费了" + container.pop().id + " 只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

// 产品
class Chicken {
    int id;  // 产品编号

    public Chicken(int id) {
        this.id = id;
    }
}

// 缓冲区
class SynContainer {
    // 需要一个容器大小
    Chicken[] chickens = new Chicken[10];
    int count = 0; // 计数器

    // 生产者放入产品
    public synchronized void push(Chicken chicken) throws InterruptedException {
        // 如果容器满了,就需要等待消费
        if (count == chickens.length) {
            // 通知消费者消费 生产者等待
            this.wait();
        }
        // 如果没有满,就需要丢入产品
        chickens[count] = chicken;
        count++;
        // 通知消费者消费  notifyAll()唤醒一个对象上所有调用wait()方法的线程
        this.notifyAll();
    }

    // 消费者消费产品
    public synchronized Chicken pop() throws InterruptedException {
        // 判断能否消费
        if (count == 0) {
            // 等待生产者生产 消费者等待
            this.wait();
        }
        // 如果可以消费
        count--;
        Chicken chicken = chickens[count];

        // 吃完了 通知生产者生产
        this.notifyAll();
        return chicken;
    }
}

信号灯法

package com.syn;

// 生产者消费者模型:利用标志位解决,信号灯法
public class TestPC {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}

// 生产者 演员
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2==0){
                this.tv.play("快乐大本营播放中");
            }else {
                this.tv.play("抖音,记录美好生活");
            }
        }
    }
}

// 消费者 观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

// 产品 节目
class TV {
    // 演员表演 观众等待
    // 观众观看 演员等待
    String voice;
    boolean flag;

    // 表演
    public synchronized void play(String voice) {
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了:" + voice);
        // 通知观众观看
        this.notifyAll();
        this.voice = voice;
        this.flag = !this.flag;
    }

    // 观看
    public synchronized void watch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了:" + voice);
        // 通知演员表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}

线程池

背景:经常创建和销段、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。

思路:提前创建好多个线程,放入线程涊中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公式交通工具。

好处:

使用:

package com.syn;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {
    public static void main(String[] args) {
        // 创建线程池 参数为 线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);

        // 执行
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        // 关闭连接
        service.shutdown();
    }
}

class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

原文:https://www.cnblogs.com/bigllxx/p/15154925.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!