public class JavaTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main start");
MyThread thread = new MyThread();
Thread a = new Thread(thread, "A");
Thread b = new Thread(thread, "B");
a.start();
b.start();
System.out.println("main end");
}
}
class MyThread implements Runnable {
private int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName() + " run enter i = " + i);
synchronized(this){
System.out.println(Thread.currentThread().getName() + " synchronized >>>>>>> i = " + i);
for (; i < 5; i++) {
//for (i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
}
}
System.out.println(Thread.currentThread().getName() + " run exit");
}
}
输出结果: main start main end A run enter i = 0 B run enter i = 0 A synchronized >>>>>>> i = 0 A synchronized loop 0 A synchronized loop 1 A synchronized loop 2 A synchronized loop 3 A synchronized loop 4 A run exit B synchronized >>>>>>> i = 5 // 为什么i的值是5而不是0呢? 这样不就和static成员变量一样了? B run exit
------解决方案-------------------- Thread a = new Thread(thread, "A"); //a线程调用的是thread对象的run方法 Thread b = new Thread(thread, "B"); //b线程调用的也是thread对象的run方法 两个线程使用的都是同一个thread对象,所以两个线程之间相互产生影响