被synchronized块修饰的类成员变量和声明为static的类成员变量一样?
实例如下,定义了一个线程类MyThread,含有一个成员变量i,没有声明为static,为什么在synchronized块内操作后,类对象B得到的i值是上一个类对象A修改过的值呢?
这样不就和static类成员一样了吗?synchronized有此作用?
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");
}
}
package com.cybersoft.dsan.test;
public class JavaTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("main start");
MyThread aa = new MyThread("A");
MyThread bb = new MyThread("B");
Thread a = new Thread(aa);
Thread b = new Thread(bb);
a.start();
b.start();
System.out.println("main end");
}
}
class MyThread implements Runnable {
private String threadName;
public MyThread(String threadName){
this.threadName = threadName;
}
private int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(threadName + " run enter i = "
+ i);
synchronized (this) {
System.out.println(threadName
+ " synchronized >>>>>>> i = " + i);
for (; i < 5; i++) {
// for (i = 0; i < 5; i++) {
System.out.println(threadName
+ " synchronized loop " + i);
}
}
System.out.println(threadName + " run exit");
}
}