本程序中的java环境是jdk1.8,之前的javajava多线程学习一到六的环境也是jdk1.8
程序中的幽灵:隐蔽的错误
package rs.thread.day0504;
/**
* @auther rs
* @date 2019/5/4 16:23
* @email 529811807@qq.com
* @weixinhao javawjs
*/
public class Test06_error {
public static void main(String[]args){
int javawjs = 1073741827;
int javawjs__1 = 1431655768;
System.out.println(javawjs);
System.out.println(javawjs__1);
int ave = ( javawjs + javawjs__1 ) / 2 ;
System.out.println(ave);
}
}
相加后,平均值大约在12亿左右,,以下是错误问题
错误的原因是因为int是溢出了,在实际生产环境中这类问题不让你耗上几个通宵,你也难以有眉目
并发下的ArrayList
我们都知道ArrayList是线程不安全的,在多线程中,会引起那些问题呢?
package rs.thread.day0504;
import java.util.ArrayList;
/**
* @auther rs
* @date 2019/5/4 16:29
* @email 529811807@qq.com
* @weixinhao javawjs
*/
public class Test07_ArrayList implements Runnable {
// static ArrayList list = new ArrayList(2000000);
static ArrayList list = new ArrayList();
public static void main(String[]args) throws InterruptedException {
Thread t1 = new Thread(new Test07_ArrayList());
Thread t2 = new Thread(new Test07_ArrayList());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(list.size());
}
@Override
public void run() {
for(int j = 0; j< 1000000 ; j++){
list.add(j);
}
}
}
会有三种结果产生程序正常ArrayList的最终大小是2000000,这说明即使并行程序有问题,也不可能每次都会有这个结果
出现错误的值,少于2000000,这是一种隐蔽的情况
3.程序抛出异常,就是初始化的时候,数组长度是10,这种情况,是因为扩容过程中,内部一致性破坏,但由于没有锁的保护,另外一个线程访问不到一致性的内部状态导致,越界问题
解决办法可以用
1. Vector 代替 ArrayList
2. Collections.synchronizedList()
并发包下的HashMap
我们都知道HashMap是线程不安全的,在多线程中,会引起那些问题呢?
package rs.thread.day0504;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/**
* @auther rs
* @date 2019/5/4 16:29
* @email 529811807@qq.com
* @weixinhao javawjs
* 解决办法可以用
* 1. Vector 代替 ArrayList
* 2. Collections.synchronizedList()
*/
public class Test08_HashMap implements Runnable {
static HashMap maps = new HashMap();
public Test08_HashMap(){}
int startInt =0;
public Test08_HashMap(int startInt){
this.startInt = startInt;
}
public static void main(String[]args) throws InterruptedException {
Thread t1 = new Thread(new Test08_HashMap(0));
Thread t2 = new Thread(new Test08_HashMap(1));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(maps.size());
}
@Override
public void run() {
for(int j = startInt; j< 1000000 ; j+=2){
maps.put(Integer.toString(j),Integer.toString(j));
}
}
}
会有以下后果产生
1.出现转换异常
2.出现隐蔽结果
解决办法用
1. Collections.synchronizedMap()
2. ConcurrentHashMap
欢迎转载,转载请注明出处!
github: rs1314
欢迎关注共公众号微信 : java微技术
分享我的学习之路和各种java技术,教程资料