静态同步函数

来源:互联网 发布:外星人 台式机 知乎 编辑:程序博客网 时间:2024/05/22 00:26
 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();

}

}


0 0
原创粉丝点击