Java JUC

volatile 关键字-内存可见性

package com.atguigu.juc;

/**
* 一、volatile 关键字:当多个线程操作共享数据时,可以保存内存中的数据可见。
*              相较于 synchronized 是一种较为轻量级的同步策略
*
* 注意:
* 1.volatile 不具备“互斥性”
* 2.volatile 不能保证变量的“原子性”
*
*/
public class TestVolatile {

   public static void main(String[] args) {
       ThreadDemo td = new ThreadDemo();
       new Thread(td).start();
       while (true) {
           if (td.isFlag()) {
               System.out.println("--------------------");
               break;
           }
       }
   }

}

class ThreadDemo implements Runnable {

   private volatile boolean flag = false;

   @Override
   public void run(){
       try {
           Thread.sleep(200);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       flag = true;
       System.out.println("flag=" + isFlag());
   }

   public boolean isFlag() {
       return flag;
   }

   public void setFlag(boolean flag) {
       this.flag = flag;
   }

}

原子变量-CAS算法

package com.atguigu.juc;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 一、i++ 的原子性问题:i++的操作实际上分为三个步骤“读-改-写”
 *      int i = 10;
 *      i = i++;//10
 *
 *      int nTemp;
 * 	    nTemp = i;
 *  	i = i+1;
 * 	    return nTemp;
 *
 * 二、原子变量:jdk1.5之后 java.util.concurrent.atomic 包下提供了常用的原子变量:
 *      1.volatile 保证内存可见性
 *      2.CAS(Compare-And-Swap) 算法保证数据的原子性
 *          CAS 算法是硬件对于并发操作共享数据的支持
 *          CAS 包含了三个操作数:
 *              内存值 V
 *              预估值 A
 *              更新值 B
 *              当且仅当 V==A 时,V = B,否则,将不做任何操作
 *
 */
public class TestAtomicDemo {
    public static void main(String[] args) {
        AtomicDemo ad = new AtomicDemo();
        for (int i = 0; i < 10; i++) {
            new Thread(ad).start();
        }
    }
}

class AtomicDemo implements Runnable {

//    private volatile int serialNumber = 0;

    private AtomicInteger serialNumber = new AtomicInteger();

    public int getSerialNumber() {
        return serialNumber.getAndIncrement();
    }

    @Override
    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + ":" + getSerialNumber());
    }
}


package com.atguigu.juc;

/**
 * 模拟CAS算法
 */
public class TestCompareAndSwap {

    public static void main(String[] args) {

        final CompareAndSwap cas = new CompareAndSwap();

        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int expectedValue = cas.get();
                    boolean b = cas.compareAndSet(expectedValue, (int) (Math.random() * 101));
                    System.out.println(b);
                }
            }).start();
        }
    }
}

class CompareAndSwap{
    private int value;

    //获取内存值
    public synchronized int get(){
        return value;
    }

    //比较
    public synchronized int compareAndSwap(int expecteValue, int newValue) {
        int oldValue = value;
        if (oldValue == expecteValue) {
            this.value = newValue;
        }
        return oldValue;
    }

    //设置
    public synchronized boolean compareAndSet(int expectedVale, int newValue) {
        return expectedVale == compareAndSwap(expectedVale, newValue);
    }

}

ConcurrentHashMap锁分段机制

package com.atguigu.juc;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * CopyOnWriteArrayList: "写入时复制"
 * 注意:添加操作多时,效率低,每次添加时都会进行复制,开销会很大。
 * 并发迭代操作多时,可以提高效率
 */
public class TestCopyOnWriteArrayList {
    public static void main(String[] args) {
        HelloThread ht = new HelloThread();

        for (int i = 0; i < 10; i++) {
            new Thread(ht).start();
        }
    }

}


class HelloThread implements Runnable {

//    private static List<String> list = Collections.synchronizedList(new ArrayList<>());

    private static List<String> list = new CopyOnWriteArrayList<>();
    static {
        list.add("AA");
        list.add("BB");
        list.add("CC");
    }

    @Override
    public void run() {
        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
            list.add("AA");
        }
    }
}

CountDownLatch闭锁

package com.atguigu.juc;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch: 闭锁,在完成某些运算时,只有其他所有线程的运算全部完成,当前运算才继续执行
 */
public class TestCountDownLatch {

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(5);
        LatchDemo ld = new LatchDemo(latch);

        long start = System.currentTimeMillis();

        for (int i = 0; i < 5; i++) {
            new Thread(ld).start();
        }

        latch.await();

        long end = System.currentTimeMillis();
        System.out.println("-----------"+(end - start));
    }
}


class LatchDemo implements Runnable {

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                for (int i = 0; i < 50000; i++) {
                    if (i % 2 == 0) {
                        System.out.println(i);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    }
}

实现Callable接口

package com.atguigu.juc;

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

/**
 * 创建执行线程的方式三:实现Callable接口
 *      相较于实现Runnable接口的方式,方法可以有返回值,并且可以抛出异常
 *      执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果
 *      FutureTask 是 Future 接口的实现类
 */
public class TestCallable {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadDemo1 td = new ThreadDemo1();
        //1.执行Callable方式,需要FutureTask实现类的支持,用于接收运算结果
        FutureTask<Integer> result = new FutureTask<>(td);

        new Thread(result).start();


        //2.接收运算后的结果
        //FutureTask 也可用于 闭锁
        System.out.println(result.get());
        System.out.println("---------------------------------");

    }
}

class ThreadDemo1 implements Callable<Integer>{


    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= 100; i++) {
            sum += i;
        }
        return sum;
    }
}


/*class ThreadDemo implements Runnable {

    @Override
    public void run() {

    }
}*/

Lock同步锁

package com.atguigu.juc;

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

/**
 * 一、用于解决线程安全问题的方式:
 * synchronized:隐式锁
 * 1.同步代码块
 *
 * 2.同步方法
 *
 * jdk1.5后:
 * 3.同步锁Lock
 * 注意:这是一个显示锁,需要通过lock()方法上锁,必须通过unlock()方法释放锁
 */
public class TestLock {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(ticket,"1号").start();
        new Thread(ticket,"2号").start();
        new Thread(ticket,"3号").start();

    }
}

class Ticket implements Runnable {

    private int tick = 100;

    private Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            lock.lock();
            try {
                if (tick > 0) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread() + "完成售票,余票为:" + --tick);
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

生产者消费者案例-虚假唤醒

Condition控制线程通信

package com.atguigu.juc;

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

/**
 * 生产者和消费者案例
 */
public class TestProductAndConsumer {

    public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Productor productor = new Productor(clerk);
        Consumer consumer = new Consumer(clerk);

        new Thread(productor, "生产者A").start();
        new Thread(consumer, "消费者B").start();

        new Thread(productor, "生产者C").start();
        new Thread(consumer, "消费者D").start();

    }

}

//店员
class Clerk {

    private int product = 0;

    private Lock lock = new ReentrantLock();

    //通过lock实例获取Condition对象,用于线程通信
    private Condition condition = lock.newCondition();

    //进货
    public void get(){
        //使用同步锁替代synchronized
        lock.lock();
        try {
            /*
                如果使用if,线程被唤醒后,不会进行判断,如果有多个线程等待在此处,唤醒之后
                多个线程执行会导致错误
            */
            //为了避免虚假唤醒问题,应该总是使用在循环中
            while (product >= 1) {
                System.out.println("产品已满");
                try {
                    //使用同步锁时,需要使用Condition对象进行线程通讯
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //保证此处代码一定执行,否则可能会存在某线程等待且无法被唤醒
            System.out.println(Thread.currentThread().getName() + ":" + ++product);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    //卖货
    public  void sale(){
        lock.lock();

        try {
            while (product <= 0) {
                System.out.println("缺货");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName() + ":" + --product);
            condition.signalAll();
        } finally {
            lock.unlock();
        }

    }

}

//生产者
class Productor implements Runnable{
    private Clerk clerk;

    public Productor(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.get();
        }
    }
}

//消费者
class Consumer implements Runnable {

    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

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

线程八锁

package com.atguigu.juc;

/**
 * 题目:判断打印的"one" or "two"
 * 1.两个普通同步方法,两个线程,标准打印,打印? //one  two
 * 2.新增Thread.sleep()给getOne(),打印? // one  two
 * 3.新增普通方法getThree(),打印? // three  one  two
 * 4.两个普通的同步方法,两个Number对象,打印? // two  one
 * 5.修改getOne() 为静态同步方法,打印? // two  one
 * 6.修改getTwo() 为静态同步方法,一个number对象,打印? // one  two
 * 7.一个是静态同步方法,一个是非静态 同步方法,两个Number对象? // two  one
 * 8.两个静态同步方法,两个number对象,打印? // one  two
 * 
 * 线程八锁的关键:
 * 1.非静态方法的锁默认为this,静态方法的锁为对应的Class实例
 * 2.在某一时刻内,只能有一个线程持有锁,无论有几个方法
 */
public class TestThread8Monitor {

    public static void main(String[] args) {
        Number number = new Number();
        Number number2 = new Number();

        new Thread(new Runnable() {
            @Override
            public void run() {
                number.getOne();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
//                number.getTwo();
                number2.getTwo();
            }
        }).start();

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                number.getThree();
//            }
//        }).start();
    }
}

class Number{

    public static synchronized void getOne() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("one");
    }

    public static synchronized void getTwo() {
        System.out.println("two");
    }

//    public void getThree() {
//        System.out.println("three");
//    }
}

线程按序交替

package com.atguigu.juc;

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

/**
 * 编写一个程序,开启3个线程,这三个线程的ID分别为A、B、C,每个线程将自己的ID打印10次,要求输出的结果必须按顺序显示
 * 如:ABCABCABC
 */
public class TestABCAlternate {

    public static void main(String[] args) {
        AternateDemo ad = new AternateDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 20; i++) {
                    ad.loopA(i);
                }
            }
        }, "A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 20; i++) {
                    ad.loopB(i);
                }
            }
        }, "B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <= 20; i++) {
                    ad.loopC(i);
                    System.out.println("-----------------------");
                }
            }
        }, "C").start();
    }

}


class AternateDemo{
    //表示当前正在执行线程的标记
    private int number = 1;

    private Lock lock = new ReentrantLock();

    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    /**
     *
     * @param totalLoop 循环第几轮
     */
    public void loopA(int totalLoop) {
        lock.lock();
        try{
            //1.判断
            if (number != 1) {
                condition1.await();
            }
            //2.打印
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
            }
            //3.唤醒
            number = 2;
            condition2.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

    public void loopB(int totalLoop) {
        lock.lock();
        try{
            //1.判断
            if (number != 2) {
                condition2.await();
            }
            //2.打印
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
            }
            //3.唤醒
            number = 3;
            condition3.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }

    public void loopC(int totalLoop) {
        lock.lock();
        try{
            //1.判断
            if (number != 3) {
                condition3.await();
            }
            //2.打印
            for (int i = 0; i < 20; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
            }
            //3.唤醒
            number = 1;
            condition1.signal();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.unlock();
        }
    }
}

ReadWriteLock读写锁

package com.atguigu.juc;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWriteLock:读写锁
 * 写写/读写 需要互斥
 * 读读  不需要互斥
 */
public class TestReadWriteLock {

    public static void main(String[] args) {
        ReadWriteLockDemo rw = new ReadWriteLockDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                rw.set((int) (Math.random() * 101));
            }
        },"write").start();

        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    rw.get();
                }
            },"read").start();
        }
    }


}

class ReadWriteLockDemo{
    private int number = 0;

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    //读取
    public void get() {
        lock.readLock().lock();
        try{
            System.out.println(Thread.currentThread().getName() + ":" + number);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.readLock().unlock();
        }

    }

    //写
    public void set(int number) {
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName());
            this.number = number;
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            lock.writeLock().unlock();
        }
    }
}

线程池

package com.atguigu.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
* 一、线程池:提供了一个线程队列,队列中保存着所有等待状态的线程。避免了创建于销毁的额外开销,提高了响应的速度
*
* 二、线程池的体系结构:
* java.util.concurrent.Executor: 负责线程的使用和调度的根接口
*      |--ExecutorService 子接口:线程池的主要接口
*          |--ThreadPoolExecutor  线程池实现类
*          |--ScheduledExecutorService  子接口:负责线程的调度
*              |--ScheduledThreadPoolExecutor  实现类:继承了ThreadPoolExecutor,实现了ScheduledExecutorService
*
* 三、工具类:Executors
* ExecutorService newFixedThreadPool(): 创建固定大小的线程池
* ExecutorService newCachedThreadPool(): 缓存线程池,线程池的数量不固定,可以根据需求自动的更改数量
* ExecutorService newSingleThreadExecutor(): 创建单个线程池。线程池中只有一个线程
*
* ScheduledExecutorService newScheduledThreadPool: 创建固定大小的线程池,可以延迟或定时的执行任务
*/
public class TestThreadPool {
   public static void main(String[] args) throws ExecutionException, InterruptedException {
       //1.创建线程池
       ExecutorService pool = Executors.newFixedThreadPool(5);

       List<Future<Integer>> list = new ArrayList<>();

       for (int i = 0; i < 10; i++) {
           Future<Integer> future = pool.submit(new Callable<Integer>() {
               @Override
               public Integer call() throws Exception {
                   int sum = 0;
                   for (int i = 0; i <= 100; i++) {
                       sum += i;
                   }
                   return sum;
               }
           });
           list.add(future);
       }

       pool.shutdown();

       for (Future<Integer> future : list) {
           System.out.println(future.get());
       }

//        ThreadPoolDemo tpd = new ThreadPoolDemo();
//
//        //2.为线程池中的线程分配任务
//        for (int i = 0; i < 10; i++) {
//            pool.submit(tpd);
//        }
//
//        //3.关闭线程池
//        pool.shutdown();
   }
}

class ThreadPoolDemo implements Runnable {

   private int i = 0;

   @Override
   public void run() {
       while (i <= 100) {
           System.out.println(Thread.currentThread().getName() + ":" + i++);
       }
   }
}

线程调度

package com.atguigu.juc;

import java.util.Random;
import java.util.concurrent.*;

public class TestScheduledThreadPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(5);

        for (int i = 0; i < 10; i++) {
            Future<Integer> result = pool.schedule(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    int num = new Random().nextInt(100);
                    System.out.println(Thread.currentThread().getName() + ":" + num);
                    return num;
                }
            }, 3, TimeUnit.SECONDS);
            System.out.println(result.get());
        }

        pool.shutdown();
    }
}

ForkJoinPool分支/合并框架 工作窃取

  • Fork/Join框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行join汇总
    在这里插入图片描述
  • Fork/Join 框架与线程池的区别
  • 采用“工作窃取”模式(work-stealing):
    当执行新的任务时它可以将其拆分成更小的任务执行,并将小任务加到线程队列中,然后再从一个随机线程的队列中偷一个并把它放在自己的队列中。
    如果一个线程正在执行的任务由于某些原因无法继续运行,那么该线程会处于等待状态。
    而在fork/join框架实现中,如果某个子问题由于等待另外一个子问题的完成而无法继续运行。那么处理该子问题的线程会主动寻找其他尚未运行的子问题来执行,这种方式减少了线程的等待时间,提高了性能。
package com.atguigu.juc;

import org.junit.Test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

public class TestForkJoinPool {

    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();

        ForkJoinTask<Long> task = new ForkJoinSunCalculate(0L, 1000000000L);

        Long sum = pool.invoke(task);
        System.out.println(sum);

        pool.shutdown();
    }
    //java8新特性
    @Test
    public void test1(){
        Long sum = LongStream.rangeClosed(0L, 1000000L)
                .parallel()
                .reduce(0L, Long::sum);
        System.out.println(sum);

    }
}


class ForkJoinSunCalculate extends RecursiveTask<Long> {

    private long start;
    private long end;

    private static final long THURSHOLD = 10000L;

    public ForkJoinSunCalculate(long state, long end) {
        this.start = state;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long length = end - start;
        if (length <= THURSHOLD) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else {
            long middle = (start + end) / 2;

            ForkJoinSunCalculate left = new ForkJoinSunCalculate(start, middle);
            //进行拆分,同时压入线程队列
            left.fork();

            ForkJoinSunCalculate right = new ForkJoinSunCalculate(middle + 1, end);
            right.fork();

            return left.join() + right.join();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值