本帖最后由 337091921 于 2013-5-12 18:27 编辑
为什么创建对象的位置不同,锁就不同啊。输出结果更不同啊?
class test
{
public static void main(String args [])
{
tic ti=new tic();
//tic tii=new tic();
Thread t=new Thread(ti,"线程一");
Thread t1=new Thread(ti,"线程二");
Thread t2=new Thread(ti,"线程三");
Thread t3=new Thread(ti,"线程四");
t.start();
t1.start();
t2.start();
t3.start();
}
}
class tic implements Runnable
{
private int num=100;
objectt obj =new object();//为什么要放这啊,放下面就不可以呢?
public void run(){
//objectt obj =new object();
while(true){
synchronized (obj){
if(num>0){
try
{Thread.sleep(10);
}
catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+" ======="+num--);
}
}
}
}
} |