进程让操作系统实现了并发,线程让进程内部实现了并发
进程,线程,cpu,内存
4.线程安全问题实例:
public class ThreadTest {
private static int count = 0;
public static void inc(){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count ++;
}
public static void main(String[] args) {
for (int i = 0;i<1000;i++){
new Thread(()->ThreadTest.inc()).start();
}
System.out.println("number="+count);
}
}
运行结果:
com.du.controller.ThreadTest
number=987
正确结果:1000
以上出现错误结果原因分析:每个线程有自己的私有内存,count则处于共享内存中。由于私有内存和共享内存数据不能及时同步导致以上错误结果。
解决方案:加锁synchronized ;
public class ThreadTest {
private static int count = 0;
public synchronized static void inc(){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count ++;
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0;i<1000;i++){
new Thread(()->ThreadTest.inc()).start();
}
Thread.sleep(3000);
System.out.println("number="+count);
}
}