java多线程总结

并发编程

并发编程会发生的一致性错误

public class ThreadDemo {
    static int num = -1;
    public static void main(String[] args){
        TicketDemo td = new TicketDemo();
        Thread[] threads = new Thread[10];
        for(int i = 0; i < 10; i++){
            threads[i] = new Thread(td, "顾客" + (i + 1));
            threads[i].start();
        }
    }

    static class TicketDemo implements Runnable{

        @Override
        public void  run() {
            num++;
            System.out.println(Thread.currentThread().getName() + "的票号为" + num);
        }
    }
}

在这里插入图片描述

synchronized (this)

public class ThreadDemo {
    static int num = -1;
    public static void main(String[] args){
        TicketDemo td = new TicketDemo();
        Thread[] threads = new Thread[10];
        for(int i = 0; i < 10; i++){
            threads[i] = new Thread(td, "顾客" + (i + 1));
            threads[i].start();
        }
    }

    static class TicketDemo implements Runnable{

        @Override
        public void  run() {
            synchronized (this){
                num++;
                System.out.println(Thread.currentThread().getName() + "的票号为" + num);
            }

        }
    }
}

在这里插入图片描述

synchronized 修饰方法

public class ThreadDemo {
    static int num = -1;
    public static void main(String[] args){
        TicketDemo td = new TicketDemo();
        Thread[] threads = new Thread[10];
        for(int i = 0; i < 10; i++){
            threads[i] = new Thread(td, "顾客" + (i + 1));
            threads[i].start();
        }
    }

    static class TicketDemo implements Runnable{

        @Override
        public void  run() {
            sell(); 
        }

        private synchronized void sell(){
            num++;
            System.out.println(Thread.currentThread().getName() + "的票号为" + num);
        }
    }
}

在这里插入图片描述

重入锁(ReentrantLock)

public class ThreadDemo {
    static int num = -1;
    static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args){
        TicketDemo td = new TicketDemo();
        Thread[] threads = new Thread[10];
        for(int i = 0; i < 10; i++){
            threads[i] = new Thread(td, "顾客" + (i + 1));
            threads[i].start();
        }
    }

    static class TicketDemo implements Runnable{

        @Override
        public void  run() {
            try {
                lock.lock();
                num++;
                System.out.println(Thread.currentThread().getName() + "的票号为" + num);
            }finally {
                lock.unlock();
            }
        }
    }
}

在这里插入图片描述

线程池

FixedThreadPool

public class ThreadDemo {
    static int num = -1;

    public static void main(String[] args){
        TicketDemo td = new TicketDemo();
        ExecutorService es = Executors.newFixedThreadPool(5);

        for(int i = 0; i < 10; i++){
            es.submit(td);

        }
        es.shutdown();
    }

    static class TicketDemo implements Runnable{

        @Override
        public void  run() {
            sell();
            try{
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        private synchronized void sell(){
            num++;
            System.out.println("售货员" + Thread.currentThread().getId() + "出售的票号是:" + num);
        }
    }
}

在这里插入图片描述
源码:

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

SingleThreadExecutor

源码:

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

CachedThreadPool

源码:

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

ThreadPoolExecutor

四种构造方法

ThreadPoolExecutor(int corePoolSize, 
					int maximumPoolSize, 
					long keepAliveTime, 
					TimeUnit unit, 
					BlockingDeque<Runnable> workQueue)
ThreadPoolExecutor(int corePoolSize,
                        int maximumPoolSize,
                        long keepAliveTime,
                        TimeUnit unit,
                        BlockingQueue<Runnable> workQueue,
                        ThreadFactory threadFactory)
ThreadPoolExecutor(int corePoolSize,
                        int maximumPoolSize,
                        long keepAliveTime,
                        TimeUnit unit,
                        BlockingQueue<Runnable> workQueue,
                        RejectedExecutionHandler handler)
ThreadPoolExecutor(int corePoolSize,
                        int maximumPoolSize,
                        long keepAliveTime,
                        TimeUnit unit,
                        BlockingQueue<Runnable> workQueue,
                        ThreadFactory threadFactory,
                        RejectedExecutionHandler handler)
  • corePoolSize:核心线程数,默认情况下核心线程会一直存活,即使处于闲置状态也不会受参数keepAliveTime限制。除非将allowCoreThreadTimeOut设置为true
  • maximumPoolSize:线程池所能容纳的最大线程数。超过这个数的线程将被阻塞。当任务队列为没有设置大小的LinkedBlockingQueque时,这个值无效。
  • keepAliveTime:非核心线程的闲置超时时间,超过这个时间就会被回收。
  • TimeUnit:指定keepAliveTime的单位,如TimeUnit.SECONDS。当将allowCoreThreadTimeOut设置为true时对corePoolSize生效。
  • BlockingQueue< Runnable>:线程池中的任务队列.常用的有三种队列: SynchronousQueue, LinkedBlockingQueque, ArrayBlockingQueue
  • ThreadFactory:线程工厂,提供创建新线程的功能。ThreadFactory是一个接口,只有一个方法
public interface ThreadFactory {
  Thread newThread(Runnable r);
}
  • RejectedExecutionHandler:RejectedExecutionHandler也是一个接口,只有一个方法。当线程池中的资源已经全部使用,添加新线程被拒绝时,会调用RejectedExecutionHandlerrejectedExecution方法。
public interface RejectedExecutionHandler {
  void rejectedExecution(Runnable var1, ThreadPoolExecutor var2);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值