【发布时间】:2016-07-21 11:43:50
【问题描述】:
是否可以在获取锁后从不同的类线程中更改实例变量的值。
我有一个类 ThreadTest,它有字符串测试实例变量。 在 Run 方法中,我锁定了 String 测试实例变量。
如果 JVM 已经对实例变量进行了锁定,那么为什么我能够从主线程更改它的值。
ThreadTest.class
包 com;
公共类 ThreadTest 实现 Runnable{
String test;
int i=100;
public ThreadTest(String test) {
super();
this.test = test;
}
@Override
public void run() {
// TODO Auto-generated method stub
// Thread.currentThread().dumpStack();
while(i>0)
{
synchronized(test){
System.out.println("Thrad Test Run--- "+test+" - "+i+"- -- "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i--;
}
}
}
Test.class
包 com;
公共类测试{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadTest testThread=new ThreadTest("1");
Thread thread=new Thread(testThread);
thread.setName("First Thread");
Thread thread1=new Thread(testThread);
thread1.setName("Second Thread");
thread.start();
thread1.start();
int i=100;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true)
{
//here im accessing the 'test' that is instance variable of ThreadTest.
// and First Thread alredy acquired a lock on 'test'.
//so according to the JAVA threading testThread.test=10 is not valid.
//how multiple threads are able to change the value of testThread.test
testThread.test="10";
//System.out.println("main thread...");
}
}
}
【问题讨论】:
标签: java multithreading synchronization