只有Thread-0线程输出的结果是我们期望的,而输出的是每次都累加的,这里累加的原因以后的博文会说明,那么要想得到我们期望的结果,有几种解决方案:
1、将Count中num变成count方法的局部变量;
- public class Count {
- public void count() {
- int num = 0;
- for(int i = 1; i <= 10; i++) {
- num += i;
- }
- System.out.println(Thread.currentThread().getName() + "-" + num);
- }
- }
|
2、将线程类成员变量拿到run方法中;
- public class ThreadTest4 {
- public static void main(String[] args) {
- Runnable runnable = new Runnable() {
- public void run() {
- Count count = new Count();
- count.count();
- }
- };
- for(int i = 0; i < 10; i++) {
- new Thread(runnable).start();
- }
- }
- }
|
3、每次启动一个线程使用不同的线程类,不推荐。
上述测试,我们发现,存在成员变量的类用于多线程时是不安全的,而变量定义在方法内是线程安全的。想想在使用struts1时,不推荐创建成员变量,因为action是单例的,如果创建了成员变量,就会存在线程不安全的隐患,而struts2是每一次请求都会创建一个action,就不用考虑线程安全的问题。