各位老师:
以下程序请帮忙看下,观察运行结果始终不能锁定对象,找不出原因,谢谢了。
public class TestSynchronize extends Thread {
Timer timer = new Timer();
public TestSynchronize(String name) {
super(name);
}
public static void main(String[] arg) {
TestSynchronize t1 = new TestSynchronize("t1");
TestSynchronize t2 = new TestSynchronize("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());
}
}class Timer {
public static int num = 0;
public synchronized void add(String name) {
//synchronized(this) {
num++;
try {
Thread.sleep(100);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+" num: "+num);
//}
}
}运行结果:
t1 num: 2
t2 num: 2
以下程序请帮忙看下,观察运行结果始终不能锁定对象,找不出原因,谢谢了。
public class TestSynchronize extends Thread {
Timer timer = new Timer();
public TestSynchronize(String name) {
super(name);
}
public static void main(String[] arg) {
TestSynchronize t1 = new TestSynchronize("t1");
TestSynchronize t2 = new TestSynchronize("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());
}
}class Timer {
public static int num = 0;
public synchronized void add(String name) {
//synchronized(this) {
num++;
try {
Thread.sleep(100);
} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+" num: "+num);
//}
}
}运行结果:
t1 num: 2
t2 num: 2
解决方案 »
- JavaMail的问题啊。有源码可以直接运行啊。~麻烦大家看看啊~~~~~~~~~~~~~~~~~~~~~~~~
- 无法获得JTable当前编辑单元格的坐标
- 请帮忙,我在做毕业设计
- 关于文件RadomAccess的定位,请大家帮忙
- 如果通过流把文件和信息压缩成字节流并发送?
- Jave 2D射击小游戏视频及源码
- 我的程序怎么才能在别人的机子上运行
- 用JB7编译生成EXE文件,提示:Exectuable must have a main class,是什么意思
- java如何实现上传和下载(有关书籍也可以)?
- 试验了两天——关于tomcat配置的问题——还是没弄好
- 如何使用HttpClient4.*获得网页的源代码?
- 怎样用Swing画如下图形
System.out.println(this);就看得清楚了,因为timer对象不是一个,所以没法实现互斥。
楼主可以把timer 对象定成静态的,就能实现同步了。
static Timer timer = new Timer();
package cai.thread;public class TestSynchronize extends Thread {
public static Timer timer = new Timer(); public TestSynchronize(String name) {
super(name);
} public static void main(String[] arg) {
TestSynchronize t1 = new TestSynchronize("t1");
TestSynchronize t2 = new TestSynchronize("t2");
t1.start();
t2.start();
} public void run() {
for (int i = 0; i < 5; i++)
timer.add(Thread.currentThread().getName());
}
}class Timer {
public static int num = 0; public synchronized void add(String name) {
// synchronized(this) {
num++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " num: " + num);
// }
}
}把timer定义成类变量 ,两个线程类共享它,才会同步吧,我不知道我理解的对不对
你创建了两个线程 ,每一个线程里都有一个timer,如果定义为static ,那么两个线程类 共享它,所以才会锁定。
而
TestSynchronize t1 = new TestSynchronize("t1");
TestSynchronize t2 = new TestSynchronize("t2");
创建了两个Timer对象
导致add方法的锁在两个对象上
Timer timer = new Timer();改为静态的就可以了