public class Handel1 extends Thread{
public void run(){
try{
Counter counter = Counter.getInstance();
counter.lock("Handel1");
}catch(Exception e){
e.printStackTrace();
}
}
}public class Handel2 extends Thread {
public void run(){
try{
Counter counter = Counter.getInstance();
counter.lock("Handel2");
}catch(Exception e){
e.printStackTrace();
}
}
}public class Counter {
private static Counter instance;
public static Counter getInstance(){
if(instance==null){
instance = new Counter();
}
return instance;
}
public synchronized void lock(String locker){
System.out.println(locker);
while(true){
}
}
}public class Main {
public static void main(String[] args) throws InterruptedException{
Handel1 h1 = new Handel1();
h1.start();
Handel2 h2 = new Handel2();
h2.start();
}
}小弟有如下疑问, 请大家帮忙, 谢谢!1.据说方法加锁的原理是对象加锁, 线程Handel1调用lock()时, 持有了Counter实例(instance)的对象锁, 此时Handel1不执行完lock(), 线程Handel2是不能调用lock()的, 可为什么从打印的结果来看却不是这样呢?
2.假设Counter不是单例模式, 如果Handel1, Handel2持有了两个不同的Counter实例, 则两个线程可同时调用lock() 对吗?
3.为什么Object的wait()要放在synchronized块中执行?
public void run(){
try{
Counter counter = Counter.getInstance();
counter.lock("Handel1");
}catch(Exception e){
e.printStackTrace();
}
}
}public class Handel2 extends Thread {
public void run(){
try{
Counter counter = Counter.getInstance();
counter.lock("Handel2");
}catch(Exception e){
e.printStackTrace();
}
}
}public class Counter {
private static Counter instance;
public static Counter getInstance(){
if(instance==null){
instance = new Counter();
}
return instance;
}
public synchronized void lock(String locker){
System.out.println(locker);
while(true){
}
}
}public class Main {
public static void main(String[] args) throws InterruptedException{
Handel1 h1 = new Handel1();
h1.start();
Handel2 h2 = new Handel2();
h2.start();
}
}小弟有如下疑问, 请大家帮忙, 谢谢!1.据说方法加锁的原理是对象加锁, 线程Handel1调用lock()时, 持有了Counter实例(instance)的对象锁, 此时Handel1不执行完lock(), 线程Handel2是不能调用lock()的, 可为什么从打印的结果来看却不是这样呢?
2.假设Counter不是单例模式, 如果Handel1, Handel2持有了两个不同的Counter实例, 则两个线程可同时调用lock() 对吗?
3.为什么Object的wait()要放在synchronized块中执行?
解决方案 »
- he content of element type "set" must match (领分)
- 如何取隐藏域中的值??
- stuts中如何使用frame
- jsp<==>servlet
- hibernate中session close的问题
- 急死我了。weblogic8.1装不上 Could not obtain archive information sinace it is corrupted. Error code = 9
- 求助:怎么安装uPortal?
- 一个一万人同时在线的信息港A,能用jerry吗
- 求助:org.apache.xerces.parsers.DOMParser在哪个包里?在哪里下?
- 在j2sdkee1.3上测试ejb出错,请指点
- 关于SpringAOP代理类与被代理类的疑问,有请众位高手
- 请问文本框中只允许输入数字(包括小数点)
System.out.println(locker);
while(true){}
是不是没有调用!1、给对象加锁是该道理,你可以让执行handle11时让handle12进行等待
2、不可以同时调用,是锁没有加上
3、当你对其加锁,意思是让handle12去等待
2,不可以
3.因为wait()方法是用来解决同步问题的