我正在学习带有锁的同步块。我想知道这个锁和程序中提供的某个第三方锁之间的区别。同步块上的Java线程锁
public class NewThread extends Thread {
StringBuffer sb;
NewThread(StringBuffer sb){
this.sb=sb;
}
public void run(){
synchronized(this.sb){
for(int i=0;i<1000;i++){
System.out.print(sb);
try{
Thread.sleep(5*60);
}
catch(Exception e){}
}
char c = this.sb.charAt(0);
this.sb.setCharAt(0, ++c);
}
}
public static void main(String[] args){
StringBuffer sb=new StringBuffer("A");
NewThread nt=new NewThread(sb);
NewThread nt1=new NewThread(sb);
NewThread nt2=new NewThread(sb);
nt.start();
nt1.start();
nt2.start();
}
}
如果我打算把
public void run(){
synchronized(this){
for(int i=0;i<1000;i++){
System.out.print(sb);
try{
Thread.sleep(5*60);
}
catch(Exception e){}
}
char c = this.sb.charAt(0);
this.sb.setCharAt(0, ++c);
}
}
这里在上面运行方法我在synchronized块给这个......我希望他们
之间的区别我还有一个问题,如果我们在同步块中给出锁对象,并且我们没有在该块内使用该对象,那么我们是否会观察到与正常块相比的任何特定事物
谢谢我的理解..但我没有得到共享锁或共享锁..可以解释一下 – satheesh 2011-04-13 05:01:41
@satheesh我不知道这是你想要的:在一个同步的多线程/进程系统中,通常只有一种资源可以存在一个锁。它用于控制共享对象。在Linux中,锁和共享对象是分开的。在Java中,每个对象都有自己的锁(可以在类Object的源代码中找到)。也许在linux中,我们可以说一个锁被一些进程共享,因为锁和进程/线程之间没有关系。但在Java中,由于每个对象都有自己的锁,因此不需要明确地共享锁。该锁由对象隐式维护。随意问。 – 2011-04-13 05:15:15
确定我明白..但是每一个你与Linux有关的事情,我有点困惑 – satheesh 2011-04-13 05:40:39