程序运行的时候,内存主要由如下部分组成:java
附一张图片,会对java虚拟机有个总体的认识;
多线程
图片来自https://www.zybuluo.com/867976167/note/51071ide
当多个线程执行同一个方法的时候,函数
何时可能会出现异常结果:url
多个线程共享一块内存区域,在不加任何保护状况下,对其操做;spa
何时可能会获得正确的结果:线程
不使用共享内存,每一个线程内存空间相互独立;code
多线程共享一块内存区域,可是对这块共享区域加锁访问;对象
状况一(多个线程共享一块内存区域,在不加任何保护状况下,对其操做):blog
写一个含静态方法的类,求和,方法内用了一个静态全局s(多个线程能够同时访问):
package com.pichen.java.static_; public class StaticTest { private static int s = 0; public static int sum(int n){ s = 0; for(int i = 0; i <= n; i++){ s += i; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } return s; } }
写一个Thread,调用上面的静态方法:
package com.pichen.java.static_; public class ThreadCount implements Runnable{ @Override public void run() { while(true){ System.out.println(Thread.currentThread().getName() +":" +StaticTest.sum(100)); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }
写个Main函数,起三个线程,观察运行结果,基本都是错误的:
package com.pichen.java.static_; public class Main { public static void main(String[] args) { ThreadCount t1 = new ThreadCount(); new Thread(t1).start(); ThreadCount t2 = new ThreadCount(); new Thread(t2).start(); ThreadCount t3 = new ThreadCount(); new Thread(t3).start(); } }
运行结果不符合预期:
Thread-0:13968 Thread-1:13968 Thread-2:13968 Thread-0:13033 Thread-1:13033 Thread-2:13033 Thread-1:14725 Thread-0:14725
缘由:多个线程同时对静态全局变量s进行操做致使;
ps:这里的例子是静态全局变量s,其实有不少种状况会引发结果异常问题,如在main方法中new出了一个对象,new出来的对象是存放在堆中的,多个线程共享,此时若是多线程同时操做该对象的话,也是有可能产生错误结果;
状况二(不使用共享内存,每一个线程内存空间相互独立):
修改静态sum方法,使用局部变量s,以下:
package com.pichen.java.static_; public class StaticTest { private static int s = 0; public static int sum(int n){ int s = 0; for(int i = 0; i <= n; i++){ s += i; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } return s; } }
运行程序,结果正确:
Thread-1:5050 Thread-0:5050 Thread-2:5050 Thread-0:5050 Thread-2:5050 Thread-1:5050 Thread-0:5050
状况三(多线程共享一块内存区域,可是对这块共享区域加锁访问):
package com.pichen.java.static_; public class StaticTest { private static int s = 0; public synchronized static int sum(int n){ s = 0; for(int i = 0; i <= n; i++){ s += i; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } return s; } }
@author 风同样的码农
@blog_urlhttp://www.cnblogs.com/chenpi/
运行程序,结果正确:
Thread-1:5050 Thread-0:5050 Thread-2:5050 Thread-0:5050 Thread-2:5050 Thread-1:5050 Thread-0:5050