2008-05-06
synchronized的作用(三)
b、锁定一个对象或方法,它是静态的
这样锁定,它锁定的是对象所属的类
等同于
测试:
目标类:
线程类:调用不同的方法,于是建立了两个线程类
调用:
这样锁定,它锁定的是对象所属的类
public synchronized static void execute(){
//...
}
等同于
public class TestThread {
public static void execute(){
synchronized(TestThread.class){
//
}
}
}
测试:
目标类:
public class TestThread {
private static Object lock=new Object();
public synchronized static void execute(){ //同步静态方法
for(int i=0;i<100;i++){
System.out.println(i);
}
}
public static void execute1(){
for(int i=0;i<100;i++){
System.out.println(i);
}
}
public void test(){
execute(); //输出是有序的,说明是同步的
//execute1(); //输出是无须的,说明是异步的
}
}
线程类:调用不同的方法,于是建立了两个线程类
public class ThreadA implements Runnable{
public void run() {
TestThread.execute();//调用同步静态方法
}
}
public class ThreadB implements Runnable{
public void run() {
TestThread test=new TestThread();
test.test();//调用非同步非静态方法
}
}
调用:
Runnable runabbleA=new ThreadA(); Thread a=new Thread(runabbleA,"A"); a.start(); Runnable runabbleB=new ThreadB(); Thread b=new Thread(runabbleB,"B"); b.start();
发表评论
- 浏览: 7033 次
- 性别:

- 来自: 佛山

- 详细资料
搜索本博客
链接
最新评论
-
基于struts2+spring+hiber ...
刚接触Jmesa,楼主可否将上面的完整工程发给我一份,以效学习? 我的邮箱:20 ...
-- by java_eye_2008 -
JAVA生成缩略图
targetW45456546464646464646
-- by shenxiaolei






评论排行榜