读书人

多线程-静态同步函数用的是哪一种锁呢

发布时间: 2012-08-30 09:55:54 作者: rapoo

多线程--静态同步函数用的是哪一种锁呢?

?

/**

多线程--静态同步函数用的是哪一种锁呢?


通过验证 发现不再是this ?因为静态方法中也不可以定义this


静态近内存时 内存中没有本类对象 但是一定有该类对应的自己码文件对象

类名.class ?该对象的类型是Class


静态的同步方法 使用的是该方法所在类的自己码文件对象 类名.class



*/


class Ticket implements Runnable

{

private static int ticketNum = 100;

boolean flag = true;


public void run(){

if(flag){

while(true){

synchronized(Ticket.class){

if(ticketNum>0){

try{

Thread.sleep(10);

}catch(Exception e){

}

System.out.println(Thread.currentThread().getName()+"code:..." + ticketNum--);

}

}

}

}else{

while(true){

show();

}

}

}


public static synchronized void show(){

if(ticketNum>0){

try{

Thread.sleep(10);

}catch(Exception e){

}

System.out.println(Thread.currentThread().getName()+"show:..." + ticketNum--);

}

}


}


class ?StaticMathodDemo

{

public static void main(String[] args)?

{


Ticket t = new Ticket();


Thread t1 = new Thread(t);//创建了一个线程

Thread t2 = new Thread(t);//创建了一个线程

t1.start();

try{

Thread.sleep(10);

}catch(Exception e){


}

t.flag = false;

t2.start();


}

}


读书人网 >编程

热点推荐