之前遇到过的问题
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);
}
}