JUC并发编程

什么是 JUC

https://blog.csdn.net/weixin_44491927/article/details/108560692?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162942786716780265487561%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=162942786716780265487561&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-108560692.pc_search_all_es&utm_term=JUC%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E7%8B%82%E7%A5%9E&spm=1018.2226.3001.4187

线程和进程

Java默认有几个线程?
2个,main,GC
Java无法直接操作硬件,通过本地方法,底层C++,开启线程

并发和并行

线程状态

public enum State {
        /**
         * Thread state for a thread which has not yet started.
         */
        NEW,

        /**
         * Thread state for a runnable thread.  A thread in the runnable
         * state is executing in the Java virtual machine but it may
         * be waiting for other resources from the operating system
         * such as processor.
         */
        RUNNABLE,

        /**
         * Thread state for a thread blocked waiting for a monitor lock.
         * A thread in the blocked state is waiting for a monitor lock
         * to enter a synchronized block/method or
         * reenter a synchronized block/method after calling
         * {@link Object#wait() Object.wait}.
         */
        BLOCKED,

        /**
         * Thread state for a waiting thread.
         * A thread is in the waiting state due to calling one of the
         * following methods:
         * <ul>
         *   <li>{@link Object#wait() Object.wait} with no timeout</li>
         *   <li>{@link #join() Thread.join} with no timeout</li>
         *   <li>{@link LockSupport#park() LockSupport.park}</li>
         * </ul>
         *
         * <p>A thread in the waiting state is waiting for another thread to
         * perform a particular action.
         *
         * For example, a thread that has called <tt>Object.wait()</tt>
         * on an object is waiting for another thread to call
         * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
         * that object. A thread that has called <tt>Thread.join()</tt>
         * is waiting for a specified thread to terminate.
         */
        WAITING,

        /**
         * Thread state for a waiting thread with a specified waiting time.
         * A thread is in the timed waiting state due to calling one of
         * the following methods with a specified positive waiting time:
         * <ul>
         *   <li>{@link #sleep Thread.sleep}</li>
         *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
         *   <li>{@link #join(long) Thread.join} with timeout</li>
         *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
         *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
         * </ul>
         */
        TIMED_WAITING,

        /**
         * Thread state for a terminated thread.
         * The thread has completed execution.
         */
        TERMINATED;
    }

sleep/wait区别

1.不同类
wait=>Object
sleep=>Thread
2.关于锁的释放
wait会释放,sleep不会释放
3.使用范围
wait必须在同步代码块中
sleep可以在任何地方
4.是否需要捕获异常
wait不需要
sleep要捕获异常

lock锁(重点)

Synchronized

公平锁:先来后到
非公平锁:可以插队

public ReentrantLock() {
        sync = new NonfairSync(); //非公平
    }

    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

lock和synchronized区别

  • synchronized内置关键字,lock是一个java类
  • synchronized 无法判断获取锁的状态,lock可以判断是否获取到锁
  • synchronized会自动释放锁,lock必须手动释放锁,否则死锁
  • synchronized 可重入锁,不可以中断,非公平;lock,可重入锁,可以判断锁,非公平
  • synchronized 适合少量代码,lock适合大量代码同步

锁是什么?如何判断锁的是谁

生产者消费者模式

public class ThreadTest {
    public static void main(String[] args) {
        Product product = new Product();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}

class Product {
    private int water = 0;

    // + 1
    public synchronized void increment() throws InterruptedException {
        //等待
        if (water != 0) {
            this.wait();
        }
        //业务
        water++;
        System.out.println(Thread.currentThread().getName()+"=>"+water);
        //通知
        this.notifyAll();
    }

    // - 1
    public synchronized void decrement() throws InterruptedException {
        //等待
        if (water == 0) {
            this.wait();
        }
        //业务
        water--;
        System.out.println(Thread.currentThread().getName()+"=>"+water);
        //通知
        this.notifyAll();
    }
}

加入变成A,B,C,D四个线程,虚假唤醒
将if改为while

public class ThreadTest {

    public static void main(String[] args) {
        Product product = new Product();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    product.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

class Product {
    private int water = 0;

    // + 1
    public synchronized void increment() throws InterruptedException {
        //等待
        while (water != 0) {
            this.wait();
        }
        //业务
        water++;
        System.out.println(Thread.currentThread().getName()+"=>"+water);
        //通知
        this.notifyAll();
    }

    // - 1
    public synchronized void decrement() throws InterruptedException {
        //等待
        while (water == 0) {
            this.wait();
        }
        //业务
        water--;
        System.out.println(Thread.currentThread().getName()+"=>"+water);
        //通知
        this.notifyAll();
    }
}

JUC版生产者和消费者

public class ThreadTest {

    public static void main(String[] args) {
        Product product = new Product();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.increment();

            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.decrement();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.increment();
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.decrement();
            }
        },"D").start();
    }

}

class Product {
    private int water = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    // + 1
    public  void increment() {
        lock.lock();
        try {
            //等待
            while (water != 0) {
                condition.await();
            }
            //业务
            water++;
            System.out.println(Thread.currentThread().getName()+"=>"+water);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // - 1
    public  void decrement() {
        lock.lock();
        try {
            //等待
            while (water == 0) {
                condition.await();
            }
            //业务
            water--;
            System.out.println(Thread.currentThread().getName()+"=>"+water);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

Condition精准通知,唤醒

public class ThreadTest {

    public static void main(String[] args) {
        Product product = new Product();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                product.printB();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {

                product.printC();

            }
        },"C").start();

    }

}

class Product {
    private int water = 1; //1,2,3

    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    // + 1
    public  void printA() {
        lock.lock();
        try {
            //等待
            while (water != 1) {
                condition1.await();
            }
            //业务
            System.out.println(Thread.currentThread().getName()+"=>AAAAAA");
            water = 2;
            //通知
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // - 1
    public  void printB() {
        lock.lock();
        try {
            //等待
            while (water != 2) {
                condition2.await();
            }
            //业务
            System.out.println(Thread.currentThread().getName()+"=>BBB");
            water = 3;
            //通知
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void printC() {
        lock.lock();
        try {
            //等待
            while (water != 3) {
                condition3.await();
            }
            //业务
            System.out.println(Thread.currentThread().getName()+"=>CCCC");
            water = 1;
            //通知
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

单例模式、排序算法、生产者和消费者、死锁

8锁现象

如何判断锁的是谁!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值