实例变量与线程安全:
不共享数据:
public class NoSharedThread extends Thread { private int count = 5; public NoSharedThread(String name){ super(); this.setName(name); } @Override public void run() { super.run(); while (count > 0){ count--; System.out.println("Thread name: " + Thread.currentThread().getName() + ", count: " + count); } } } public class ThreadRunMain { public static void main(String[] args) { testSharedSafeThead(); } public static void testNoSharedThread() { NoSharedThread a = new NoSharedThread("a"); NoSharedThread b = new NoSharedThread("b"); NoSharedThread c = new NoSharedThread("c"); a.start(); b.start(); c.start(); } }
运行结果:
可见线程之间没有互相干扰,都在操作自己的count变量。
共享数据:
public class SharedThread extends Thread{ private int count = 5; public SharedThread(String name) { super(); this.setName(name); } @Override public void run() { super.run(); count--; System.out.println("Thread name: " + Thread.currentThread().getName() + ", count: " + count); } } public class ThreadRunMain { public static void main(String[] args) { testSharedThead(); } public static void testSharedThead(){ SharedThread st = new SharedThread("SharedThread"); Thread a = new Thread(st,"a"); Thread b = new Thread(st,"b"); Thread c = new Thread(st,"c"); Thread d = new Thread(st,"d"); Thread e = new Thread(st,"e"); a.start(); b.start(); c.start(); d.start(); e.start(); } }
运行结果:
可见线程之间互相干扰,产生count值一样的情况,非线程安全的问题出现。
共享数据线程安全:
public class SharedSafeThread extends Thread{ private int count = 5; public SharedSafeThread(String name) { super(); this.setName(name); } @Override public synchronized void run() { super.run(); count--; System.out.println("Thread name: " + Thread.currentThread().getName() + ", count: " + count); } } public class ThreadRunMain { public static void main(String[] args) { testSharedSafeThead(); } public static void testSharedSafeThead(){ SharedSafeThread sst = new SharedSafeThread("SharedSafeThread"); Thread a = new Thread(sst,"a"); Thread b = new Thread(sst,"b"); Thread c = new Thread(sst,"c"); Thread d = new Thread(sst,"d"); Thread e = new Thread(sst,"e"); a.start(); b.start(); c.start(); d.start(); e.start(); } }
运行结果:
可见线程之间没有互相干扰,count值没有重复,线程安全。
原文:http://www.cnblogs.com/AK47Sonic/p/7653151.html