ITeye博客

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

wststar · 2012-05-22 08:58 · JAVA基础_多线程 · 编程语言 · Markdown

/**

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

通过验证 发现不再是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();

}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。