/*
* 【【靜態同步函數】】
* 靜態同步函數,對象使用的【不是this】
* 通過驗證,發現不是this 因爲靜態方法中,不可以定義this。
*
* 靜態進內存的時候,內存中沒有本類對象,但是,一定有該類對應的字節碼文件對象
* 類名.class 該對象的類型是: Class
*
* 靜態的同步函數對象是,該類對應的字節碼文件對象 就是 類名.class
*/
class Ticket5 implements Runnable{//方式二
private static int tick=100;
boolean flag=true;
public void run(){
if(flag){
while(true){
//synchronized(this){//this 不知道爲什麼我的程序用this其實沒有出現過0
synchronized(Ticket5.class){//更換爲Ticket5.class 不在出現0 線程安全。
if(tick>0){
try{
Thread.sleep(10);//【a】
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"買票"+(tick--));
}
}
}
}
else{
while(true)
show();
}
}
public static synchronized void show(){
if(tick>0){
try{
Thread.sleep(10);//【a】
}
catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"show"+(tick--));
}
}
}
public class D_Th_test6{
public static void main(String[] args) {
Ticket4 t=new Ticket4();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
try{
Thread.sleep(10);//【a】
}
catch(Exception e){}
t.flag=false;
t2.start();
}
}
-----------------------------------------------------------------------------------------------
package _Day11;
/*
* 返回來再看看 單列設計模式
*
* 死鎖: 同步中嵌套同步
* 設計時一定要避免死鎖。
*/
//餓漢式
/*
class Single{
private static final Single s=new Single();
private Single(){}
public static void Single getInstance(){
return s;
}
}
*/
//懶漢式
class Single{
private static Single s=null;
private Single(){}
public static Single getInstance(){
if(s==null){
synchronized(Single.class){
if(s==null)
s=new Single();
}
}
return s;
}
}
public class D_Th_test7 {
}
黑馬官網: http://edu.csdn.net/heima