---
title: "多线程--静态同步函数用的是哪一种锁呢？"
author: "wststar"
date: "2012-05-22T08:58:02Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-05-21T17:56:45Z"
id: 1536519
url: "https://wststar.iteye.com/blog/1536519"
---

/\**

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

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

}

}