Java中的多线程
jopen
9年前
经常听到StringBuffer是线程安全的,String是线程不安全的,可是什么是线程安全呢,什么是线程不安全呢,这些困扰了我们这么久
,在高并发情况下,我们要注意线程安全,全局变量一般都是线程不安全,而局部变量一般都是安全的看代码
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(); } } }
这个是线程的测试类,线程启动我希望他每次拿到都是5050
看结果
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方法中
得到的结果
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