多线程加锁问题

之前遇到过的问题

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);

    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值