阳哥多线程JUC--1


1、lamda表达式

括号开始、右箭头、大括号结束

 package com.ntuzy.juc_01.zf;

public class lamdaDemo {
    @FunctionalInterface
    interface  LambdaAcount{
        int add(int x, int y);

    }
    public static void main(String[] args) {
        LambdaAcount lambdaAcount = (x,y)->{return x+y;};
        int account = lambdaAcount.add(3,5);
        System.out.println(account);
    }
}

2、线程通信(普遍方法)

多线程口诀:
1.线程操作资源类
2.判断,执行逻辑,通知
3.防止多行程的虚假唤醒,用while解决,不能用if判断
4.标志位(Condiction精准唤醒)

package com.ntuzy.juc_01.zf;
class Air {
    private int num = 0;

    public synchronized void increment() throws InterruptedException {
        //判断
        while(num != 0) {
            this.wait();
        }
        //执行逻辑
        num++;
        //通知
        System.out.println(Thread.currentThread().getName() +":  "+ num);
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        //判断
        while(num == 0) {
            this.wait();
        }
        //执行逻辑
        num--;
        //通知
        System.out.println(Thread.currentThread().getName() +":  "+ num);
        this.notifyAll();
    }
}
public class ThreadWaitNotifyDemo {


    public static void main(String[] args) {
        Air air = new Air();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        air.increment();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

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


        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        air.decrement();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

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


    }
}

3、线程通信(新版方法)

package com.ntuzy.juc_01.zf;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Air {
    private int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() {
        //判断
        lock.lock();

        try {
            while (num != 0) {
                condition.await();
            }
            //执行逻辑
            num++;
            //通知
            System.out.println(Thread.currentThread().getName() + ":  " + num);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void decrement() {
        //判断
        lock.lock();
        try {
            while (num == 0) {
                condition.await();
            }
            //执行逻辑
            num--;
            //通知
            System.out.println(Thread.currentThread().getName() + ":  " + num);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
public class ThreadWaitNotifyDemo {


    public static void main(String[] args) {
        Air air = new Air();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    air.increment();
                }

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


        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    air.decrement();
                }

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

    }
}

4、用Condiction精准唤醒线程

package com.ntuzy.juc_01.zf;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareResource {
    private int num = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            while (num != 1) {
                condition1.await();
            }
            num = 2;
            System.out.println(Thread.currentThread().getName());
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void printB() {
        lock.lock();
        try {
            while (num != 2) {
                condition2.await();
            }
            num = 3;
            System.out.println(Thread.currentThread().getName());
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void printC() {
        lock.lock();
        try {
            while (num != 3) {
                condition3.await();
            }
            num = 1;
            System.out.println(Thread.currentThread().getName());
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}

public class ConditionDemo {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.printA();
            }
        }, "A").start();

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

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

5、八锁问题
在这里插入图片描述在这里插入图片描述

package com.ntuzy.juc_01.zf;

import java.util.concurrent.TimeUnit;

class Phone {
    public static synchronized void sendEmail() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("---sendEmail");
    }

    public static synchronized void sendSMS() {
        System.out.println("---sendSMS");
    }

    public void hello() {
        System.out.println("---hello");
    }
}

public class Lock8 {
    public static void main(String[] args) throws InterruptedException {
        Phone phone = new Phone();
        Phone phone2 = new Phone();
        new Thread(() -> {
            phone.sendEmail();
        }, "name").start();
        Thread.sleep(100);
        new Thread(() -> {
            //phone.sendSMS();
//            phone.hello();
//            phone2.sendSMS();
//            phone.sendSMS();
            phone2.sendSMS();
        }, "name").start();

    }


}

6、CopyOnWriteList()、CopyOnWriteArraySet、ConcurrentHashMap并发

在这里插入图片描述

7、Callable接口

package com.ntuzy.juc_01.zf;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class MyThread implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {

        return 1024;
    }
}
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        MyThread myThread = new MyThread();
        FutureTask future = new FutureTask(myThread);
         new Thread(future,"A").start();
         new Thread(future,"B").start();
        System.out.println(future.get());
    }
}

8、CountDownLatch倒计时开始

package com.ntuzy.juc_01.zf;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch count  = new CountDownLatch(6);
        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                count.countDown();
                System.out.println(Thread.currentThread().getName() + "离开教室");
            }, String.valueOf(i)).start();
        }
        count.await();
        System.out.println(Thread.currentThread().getName() + "班长关门走人");
    }
}

9、CyclicBarrier加法计数器

package com.ntuzy.juc_01.zf;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 聚齐7颗龙珠召唤神龙
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("召唤神龙");
        });
        for (int i = 0; i < 19; i++) {
            int finalI = i;
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "召唤第:" + finalI + "龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }

            }, String.valueOf(i)).start();
        }

    }
}

10、SemaPhore信号灯

package com.ntuzy.juc_01.zf;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 3个车位,7个人的车抢位,出去一个进来一个
 */
public class SemaPhoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 7; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "抢到了" + finalI + "车位");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() + "离开了" + finalI + "车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值