这个例子就是为了说明instance和static变量被多个线程访问的结果:
1.static 的话,肯定要注意多线程的问题
2.instance的话,就看前面caller的代码怎么写了。
在多个线程的情况下,instance 变量很可能被多个线程修改过。
3.sychronized仅仅是为了保证原子操作性,对变量被多线程访问过是无法控制的
package com.tools.thread.eighth;
public class MultipleThreadTest {
public static void main(String[] args) {
final Call1 call1 = new Call1();
for (int i = 0; i < 100; i++) {
Thread Work = new Thread() {
public void run() {
//下面的注释可以去掉,察看不同的执行结果
// call1.synchronous();
call1.asynchronous();
// call1.call();
}
};
Work.start();
}
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.tools.thread.eighth;
public class Call1 {
private Call2 call2 = new Call2();
synchronized void synchronous(){
call2.print();
}
void asynchronous(){
call2.print();
}
void call(){
Call2 call3 = new Call2();
call3.print();
}
}
package com.tools.thread.eighth;
public class Call2 {
private String sharedInstanceResoure = "instanceResource" ;
private static String sharedStaticResouce = "staticResource" ;
public void print(){
setResource(getResource()+ " "+ Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName()+ ":"+getResource());
setStaticResource(getStaticResource()+ " "+ Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName()+ ":"+getStaticResource());
}
public String getResource() {
return sharedInstanceResoure;
}
public void setResource(String resource) {
this.sharedInstanceResoure = resource;
}
public String getStaticResource() {
return sharedStaticResouce;
}
public void setStaticResource(String resource) {
this.sharedStaticResouce = resource;
}
}