java并发总结

创建方式

  1. 继承Thread
  2. 实现Runnable、Callable
  3. 线程池
    1. newCachedThreadPool:适用于短期异步,线程可重用。
    2. newFixedThreadPool: 固定线程数,以共享队列的方式运行。
    3. newScheduledPool: 可以延迟运行或者定期执行。
    4. newSingleThreadExecutor 只有一个线程,当这个线程死了会重启一个新的线程代替它。

线程池参数

  • 四种线程池都是new这个对象
public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
  • 参数说明
    c o r e P o o l S i z e corePoolSize corePoolSize: 池中要保留的线程数,即使它们处于空闲状态,除非设置了allowCoreThreadTimeOut
    m a x i m u m P o o l S o z e maximumPoolSoze maximumPoolSoze: 池中允许的最大线程数.
    k e e p A l i v e T i m e keepAliveTime keepAliveTime: 当线程数大于核心时,这是多余空闲线程在终止前等待新任务的最长时间
    u n i t unit unit:keepAliveTime参数的时间单位
    w o r k Q u e u e workQueue workQueue: 用于在执行任务之前保存任务的队列。
    $$
Creates a new ThreadPoolExecutor with the given initial parameters and default thread factory and rejected execution handler. It may be more convenient to use one of the Executors factory methods instead of this general purpose constructor.
Params:
corePoolSize – the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set
maximumPoolSize – the maximum number of threads to allow in the pool
keepAliveTime – when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
unit – the time unit for the keepAliveTime argument
workQueue – the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.
Throws:
IllegalArgumentException – if one of the following holds: corePoolSize < 0 keepAliveTime < 0 maximumPoolSize <= 0 maximumPoolSize < corePoolSize
NullPointerException – if workQueue is null

阻塞线程

  1. 等待阻塞 o . w a i t o.wait o.wait:将进程放入等待队列
  2. 同步阻塞(lock)若锁被其他线程占用,当前线程放入锁池。
  3. 其他阻塞(sleep/join)

线程死亡

正常结束

run()或者call()方法执行完成,线程正常结束。

异常结束

线程抛出一个未捕获的Exception或Error

调用stop
此方法容易导致死锁。

终止线程的4种方式

  1. 正常结束
  2. 使用退出标志退出线程
    public static void solve(){
    
        ExecutorService pool = Executors.newCachedThreadPool();
        pool.execute(new Runnable() {
            public  volatile boolean exit = false;
            int aim = 0;
            @Override
            public void run() {
    //                System.out.println("Hello World "+ System.currentTimeMillis());
                while (!exit){
                    if(aim<10){
                        System.out.println(aim+" : "+System.currentTimeMillis());
                    }else{
                        exit = true;
                    }
                    aim++;
                }
            }
        });
    }
    
  3. Interrupt方法结束线程:

    线程处于阻塞状态时,调用interrupt方法会抛出中断异常,然后跳出循环状态,正常结束线程。
    若未处于阻塞状态,使用isInterrupted()判断线程的中断标志来推出循环。

      public static void func(){
        ExecutorService pool = Executors.newCachedThreadPool();
        pool.execute(new Runnable() {
            @Override
            public void run() {
                while(!Thread.currentThread().isInterrupted()){
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                        break;
                    }
                }
            }
        });
    }
    
  4. stop方法(线程不安全)

sleep与wait的区别

  1. Thread.sleep() ; Object.wait()
  2. sleep方法使程序暂停指定时间,将CPU让给其他进程,到了一定时间后自动恢复运行状态。
  3. sleep方法,线程不会释放锁。
  4. wait方法线程会放弃对象锁,进入等待锁定池,只有针对这个对象使用notify后,此线程才会准备获取对象锁进入运行状态。

start与run的区别

  1. start()启动线程,不用等待run方法体执行完成就可以直接继续执行下面的代码。
  2. Thread.start方法启动一个线程,这个线程处于就绪状态并没有运行。
  3. run是线程方法体,包含了线程的内容。run结束,线程终止。

Atomic包

public class AtomicBoolean implements java.io.Serializable {
    private static final long serialVersionUID = 4654671469794556979L;
    // setup to use Unsafe.compareAndSwapInt for updates
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long valueOffset;

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicBoolean.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile int value;
    ……

未完待续 未央书斋 温故知新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ambrosedream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值