多線程加鎖問題

之前遇到過的問題

1.多線程對ArrayList賦值

import java.util.ArrayList;


/**
 * Created by w on 2019/8/13.
 *
 * 正常是200萬
 *
 *  可能存在的問題:
 *  * 1.Thread-0" java.lang.ArrayIndexOutOfBoundsException: 73
 *  * ArrayList在擴容時候內部一致性被破壞,由於沒有鎖的保護,另一個線程訪問到不一致內部狀態;
 *  * 2.1777529,數據小於200萬
 *  * 同時兩個線程在ArrayList的同一個位置賦值
 *
 * 改進:
 * 使用線程安全的Vector代替ArrayList
 *
 */
public class ArrayListMultiThread {

    static ArrayList<Integer> al = new ArrayList<>();
    public static class AddThread implements Runnable{


        @Override
        public void run() {
            for(int i=0;i<1000000;i++){
                al.add(i);
            }
        }
    }



    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new AddThread());
        Thread t2 = new Thread(new AddThread());
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(al.size());
    }

}

 

2.多線程操作Map

/**
 * hashmap非線程安全小心嘗試
 *
 *

 */
public class HashMapMultiThread {

    static Map<String,String>  map = new HashMap<>();
    public static class AddThread implements Runnable{
        int start = 0;

        public AddThread(int start){
            this.start = start;
        }

        @Override
        public void run() {
            for(int i=start;i<100000;i+=2){
                map.put(Integer.toString(start),Integer.toBinaryString(start));

            }

        }
    }



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

        Thread t1 = new Thread(new HashMapMultiThread.AddThread(0));
        Thread t2 = new Thread(new HashMapMultiThread.AddThread(1));
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(map.toString());

    }


}

 

3.計數器加鎖

/**
 * Created bywangy on 2019/8/13.
 *
 *  *
 *  * 對計數器加鎖
 */
public class SyncTest implements Runnable{

    public static Integer i = 0;
    static SyncTest instance = new SyncTest();

    @Override
    public void run() {

        for(int j=0;j<100000;j++){

            //synchronized (i){  這樣會出現不是鎖定當前對象
            synchronized (instance){
                i++;
            }
        }
    }


    public static void mian(String[] args) throws InterruptedException {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);

    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章