class Printer implements Runnable {
private static Object lock = new Object();//把此处的static去掉,为什么程序就死锁了???
private static int current = 0;
private String content = null;
private int flag = 0;
public Printer(String content, int flag) {
this.content = content;
this.flag = flag;
}
public void run() {
int times = 0;
while (times < 19) {
synchronized (lock) {
while (current % 3 != flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(content);
times++;
Printer.current++;
lock.notifyAll();
}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
new Thread(new Printer("A", 0)).start();
new Thread(new Printer("B", 1)).start();
new Thread(new Printer("C", 2)).start();
}
}
解决方案 »
- MyEclipse8.5 Hibernate反向工程出错???
- ssh的 javax.servlet.ServletException: org/springframework/dao/PermissionDeniedDataAccessException错误
- JNI如何传递vc中带指针的参数和函数的问题
- Struts和EJB怎么弄在一块?
- 让前台提交的表单给action处理后不跳转
- spring中HibernateTemplate的使用
- tomcat 配置问题?急啊
- eclipse 中在那里能添加参数? -conf c:\resin\resin.conf
- 能不能用javamail来删除邮件服务器上的邮件?怎么删除?
- Lucene复杂分词——中英夹杂特殊符号
- 判断配置文件是否符合特定的规则
- richfaces 页面没有输入,BB中读出来的值确实0
去掉了static ,进程间的变量互不相干
不一定要使用static,保证是同一个对象即可
当然如果你用static的话,这个对象肯定就是唯一的了
使用static修饰lock表示,jvm在类加载的时候为lock分配内存,当声明多个Printer类的实例的时候,并不会去创建lock变量的副本,Printer类所有的实例都共享一个lock变量
这样理解,如果lock不使用static修饰,每声明一个Printer类,都会产生一个lock实例变量,哪么这样做你的同步就没有意义了吧个人理解,不知道对不对、期待大神拍砖