多线程高级运用

  • -多线程的六种状态: 新建状态-(即创建线程对象) 就绪状态-(即调用start方法) 阻塞状态-(即无法获得锁对象) 等待状态-(遇到wait方法) 计时状态(即遇到sleep方法) 结束状态(即代码运行完毕)
  • 线程池:Executors.newCachedThreadPool() ,默认创建一个空的池子即线程池, 当有任务时会自动创建线程对象,当任务执行完毕后,线程对象不会消失,回到线程池即重复使用

public class Test01 {
    public static void main(String[] args) throws InterruptedException {

        // 线程池的创建和使用
        //调用newCachedThreadPool 创建一个默认的线程池对象,最大长度为int类型的最大值
        //返回值为线程池的控制对象
        ExecutorService executorService = Executors.newCachedThreadPool();

        //调用submit方法创建线程池对象,因参数为接口所以,传实现类的对象
        //线程即程序要做的事,并不是每件事跟线程都一一对应,创建线程对象,谁有空谁执行任务
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"在执行");
            }
        });

        //有时创建几个任务,只显示一个线程在工作
        //原因,是因为sleep休眠时,在执行完上面任务后,又重新回到线程池,即重复使用
        //Thread.sleep(10);

        //
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"在执行");
            }
        });

        //调用shutdown 方法关闭线程池
        executorService.shutdown();



        //调用newFixedThreadPool有参构造创建对象 参数为线程池最大值
        ExecutorService executorService1 = Executors.newFixedThreadPool(10);

        executorService1.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"在执行");
            }
        });

        executorService1.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"在执行");
            }
        });

        executorService1.shutdown();

    }
}
public class Test02 {
    public static void main(String[] args) {
        //自创线程池对象

        ThreadPoolExecutor threadPoolExecutor =
         new ThreadPoolExecutor(2,
                 6,
                 4,
         TimeUnit.DAYS,new ArrayBlockingQueue<>(10),
                 Executors.defaultThreadFactory(),
                 new ThreadPoolExecutor.CallerRunsPolicy());

        //ThreadPoolExecutor.AbortPolicy()  默认拒绝策略,舍弃多余的任务并抛出异常
       //ThreadPoolExecutor.DiscardPolicy()  舍弃多余任务,但不抛出异常,不推荐使用
      //ThreadPoolExecutor.DiscardOldestPolicy()  舍弃队列中等待最久的,然后把的当前任务加入队列
     //ThreadPoolExecutor.CallerRunsPolicy()   即多余的方法交给主方法去运行
        for (int i = 0; i < 19; i++) {

            int y = i;
            threadPoolExecutor.submit(new Runnable() {

                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+y+"在执行");
                }
            });
        }
    }
}

  • volatil关键字:即强制线程每次使用时都会查看共享区域最新数据
public class Boy extends  Thread {
    //男孩线程
    @Override
    public void run() {

        try {
            Thread.sleep(100);

            share.money=90000;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class girl extends Thread {
    //女孩线程
    @Override
    public void run() {

        while (share.money==100000){

        }

        System.out.println("结婚基金不是十万了");
    }
}


public class share {
    //设置共享数据
    //volatile 关键字即线程每次使用时,都会强制看下共享内容最新数据
    //常用在共享资源数据类型前面修饰
    public static volatile int money = 100000;

}
public class Test01 {
    public static void main(String[] args) {
        //测试类

        //虽然结婚基金变了,但女孩一直没获取到最新消息
        girl girl = new girl();

        girl.start();

        Boy boy = new Boy();

        boy.start();
    }
}


  • 原子性:即一次性或多个操作,要么所有操作步骤成功且不受外界干扰而失败,要么操作全部失败,即一件事分为多个步骤,要么成功,要么失败
  • count++ 并不是一个原子性操作,即在运行过程中,有可能被其它线程抢走cpu使用权
public class Test02 {
    public static void main(String[] args) {
        //演示原子性一些方法
        //创建对象
        AtomicInteger atomicInteger = new AtomicInteger(10);

        //get() 获取当前对象的值
        int i = atomicInteger.get();
        System.out.println(i);

        //getAndIncrement()  当前对象值加一   返回值为被加前对象的值
        int andDecrement = atomicInteger.getAndIncrement();
        System.out.println(andDecrement);
        System.out.println(atomicInteger.get());


        //incrementAndGet()  当前值加一,返回值被加后的值
        int i1 = atomicInteger.incrementAndGet();
        System.out.println(i1);

        //addAndGet 当前参数值与对象参数值相加,并返回
        int i2 = atomicInteger.addAndGet(6);
        System.out.println(i2);

        //getAndSet 返回值为当前对象的值,然后方法参数再给其覆盖原来的值
        int andSet = atomicInteger.getAndSet(12);
        System.out.println(andSet);
        System.out.println(atomicInteger.get());
    }
}
  • hashmap集合,线程不安全, hashtable集合: 能保证线程安全,但效率慢 ConcurrentHashMap集合: 既能保证线程安全运行效率相对也快
public class Test03 {
    public static void main(String[] args) {

        ConcurrentMap<String,String> concurrentMap = new ConcurrentHashMap<>();
        //继承创建线程
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    concurrentMap.put(i+ " ",i+" ");
                }
            }
        }) ;
        thread.start();


        //继承创建线程
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 9; i < 110; i++) {
                    concurrentMap.put(i+ " ",i+" ");
                }
            }
        }) ;


        thread1.start();
    }
}

  • CountDownLatch 并发工具类
public class Test04 {
    public static void main(String[] args) {
        //创建对象并把它作为参数传给线程对象

        //创建等待的线程对象
        CountDownLatch countDownLatch = new CountDownLatch(3);

        //创建父母对象
        Parents parents = new Parents(countDownLatch);

        parents.setName("小美");

        parents.start();
        children1 children1 = new children1(countDownLatch);

        children1.setName("小明");
        children1 children2 = new children1(countDownLatch);

        children2.setName("小李");
        children1 children3 = new children1(countDownLatch);

        children3.setName("小王");

        children1.start();

        children2.start();

        children3.start();
    }
}

ublic class Parents extends Thread {
    private CountDownLatch countDownLatch;

    public Parents(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        //等待
        try {
            //等待的意思
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("吃完了,收拾碗筷");
    }

}

public class children1 extends Thread {


    private final CountDownLatch countDownLatch;

    public children1(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 1; i <=10; i++) {
            System.out.println(getName()+"已经吃了"+i+"了饺子了");
        }
        countDownLatch.countDown();
        //吃完后说一声,即线程结束
    }
}

public class children2 extends Thread {
    private final CountDownLatch countDownLatch;

    public children2(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 1; i <=12; i++) {
            System.out.println(getName()+"已经吃了"+i+"了饺子了");
        }
        countDownLatch.countDown();
        //吃完后说一声,即线程结束
    }
}
public class children3 extends Thread {


    private final CountDownLatch countDownLatch;

    public children3(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        for (int i = 1; i <=15; i++) {
            System.out.println(getName()+"已经吃了"+i+"了饺子了");
        }

        countDownLatch.countDown();
        //吃完后说一声,即线程结束
    }
}

  • Semaphore 可以控制访问特定资源的线程数量
public class waitfor implements Runnable {

    //创建对象,并指定最大通行数量
    Semaphore semaphore = new Semaphore(5);
    @Override
    public void run() {

        try {
            semaphore.acquire();
            System.out.println("获得通行证,并开始行驶");
            //休眠1秒
            Thread.sleep(2000);
            System.out.println("收回通行证");
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

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

        waitfor waitfor = new waitfor();
        for (int i = 0; i < 50; i++) {


            Thread thread = new Thread(waitfor);

            thread.start();
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值