常常聽到StringBuffer是線程安全的,String是線程不安全的,但是什麼是線程安全呢,什麼是線程不安全呢,這些困擾了咱們這麼久java
,在高併發狀況下,咱們要注意線程安全,全局變量通常都是線程不安全,而局部變量通常都是安全的看代碼安全
package org.thread; public class Count { private int num =0; public void getCount() { for (int i = 0; i <= 100; i++) { num += i; } System.out.println(Thread.currentThread().getName() + "============" + num); } }
這個方法是一個計數的方法,我但願他每次返回都是5050併發
package org.thread; public class ThreadTest { public static void main(String[] args) { Runnable runnable = new Runnable() { Count count = new Count(); @Override public void run() { count.getCount(); } }; for(int i = 0;i<=100;i++){ new Thread(runnable).start(); } } }
這個是線程的測試類,線程啓動我但願他每次拿到都是5050ide
看結果高併發
Thread-0============5050 Thread-2============10100 Thread-4============19336 Thread-9============39536 Thread-8============44586 Thread-6============49636 Thread-11============59736 Thread-3============24386 Thread-1============19336 Thread-15============64786 Thread-7============29436 Thread-12============54686 Thread-5============34486
Thread-0============5050這個 這有這個是我想要的,其餘數據都是多餘的
那麼如今我想獲得5050 有幾種方式性能
第一種測試
public class Count { public void getCount() { int num =0; for (int i = 0; i <= 100; i++) { num += i; } System.out.println(Thread.currentThread().getName() + "============" + num); } }
把線程
private int num =0;設置成內部變量也就是在getCount方法中
獲得的結果code
Thread-0============5050 Thread-1============5050 Thread-6============5050 Thread-2============5050 Thread-3============5050 Thread-10============5050 Thread-8============5050 Thread-7============5050 Thread-5============5050 Thread-4============5050 Thread-9============5050
這個是我想要的內存
還有一種就是
Runnable runnable = new Runnable() { @Override public void run() { Count count = new Count(); count.getCount(); } };
把
Count count = new Count();放到run方法中,每次都建立
這種方法消耗內存性能,不提倡
獲得的結果
Thread-0============5050 Thread-1============5050 Thread-6============5050 Thread-2============5050 Thread-3============5050 Thread-10============5050 Thread-8============5050 Thread-7============5050 Thread-5============5050 Thread-4============5050 Thread-9============5050