package com.RunnableDemo;
/**
* 同步函数被静态修饰后,它使用是锁是该函数所属类的字节码文件对象:类名.class,该对象的类型是Class。
*
* 静态进入内存时,内存中没有该类的对象,但一定有该类对应的字节码文件对象,这个对象是唯一的。
*
*
*
*
* */
public class ThreadRunnable implements Runnable {
private static int Ticket = 1000;
boolean flag = true;
Object obj = new Object();
@Override
public void run() {
if (flag) {
while (true)
{
synchronized (ThreadRunnable.class)// 锁
{
if (Ticket > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "__sale__" + Ticket--);
}
}
}
}
else {
while (true) {
show();
}
}
}
// 同步函数用的是所属对象的锁this
public static synchronized void show() {
while (true)
{
if (Ticket > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "__show__" + Ticket--);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
ThreadRunnable t = new ThreadRunnable();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag = false;
t2.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t3.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag =true;
t4.start();
}
}