java線程不安全類與寫法

線程不安全類

1.爲何java裏要同時提供stringbuilder和stringbuffer兩種字符串拼接類java

2.simpledateformate是線程不安全的類,若是把它做爲全局變量會有線程安全的問題,根據線程封閉原則,把它做爲局部變量就能夠了,或者用jodatime安全

jodatime使用示例

package com.alan.concurrency.example.commonUnsafe;

import com.alan.concurrency.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@ThreadSafe
public class DateFormatExample3 {

    // 請求總數
    public static int clientTotal = 5000;

    // 同時併發執行的線程數
    public static int threadTotal = 200;

    private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd");

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            final int count = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    update(count);
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    private static void update(int i) {
        log.info("{}, {}", i, DateTime.parse("20180208", dateTimeFormatter).toDate());
    }
}

3.arraylist hashset hashmap併發

2.不安全的寫法

1.先檢查再執行 if(condition(a)){handle(a);} --要注意這個a是否會被多個線程共享修改,解決辦法是鎖+雙重驗證ui

2.vector並非全部狀況下都是線程安全的,例如兩個線程,一個get,一個remove,若是同一下標的值是先remove,那麼get時就會出錯。spa

3.類的private方法會被隱式的修飾爲final的

相關文章
相關標籤/搜索