package synh;
class ThreadDemo implements Runnable{
int tickets = 100;//票數
String str = new String("");
//在一個方法裡實作同步
public void run(){
while(true){
sale();
}
}
public synchronized void sale(){
if(tickets > 0){
try{Thread.sleep(1);}catch(Exception e){}//模拟不同步的實作
System.out.println(Thread.currentThread().getName() + " is salling ticket --- " + tickets--);
}
}
}
class ThreadTest{
public static void main(String [] args){
ThreadDemo td = new ThreadDemo();
new Thread(td).start();
new Thread(td).start();
new Thread(td).start();
new Thread(td).start();
}
}
看完了線程間的同步,再看看同步方法和同步代碼塊之間的同步
package synch;
class ThreadDemo implements Runnable{
int tickets = 100;//票數
String str = new String("");
//在一個方法裡實作同步
public void run(){
if(str.equals("method")){
while(true){
sale();
}
}
else{
while(true){
synchronized(this){
if(tickets > 0){
try{Thread.sleep(1);}catch(Exception e){}
System.out.println(Thread.currentThread().getName() + " is salling ticket --- " + tickets--);
}
}
}
}
}
public synchronized void sale(){
if(tickets > 0){
try{Thread.sleep(1);}catch(Exception e){}//模拟不同步的實作
System.out.println("method: " + Thread.currentThread().getName() + " is salling ticket --- " + tickets--);
}
}
}
class ThreadTest1{
public static void main(String [] args){
ThreadDemo td = new ThreadDemo();
new Thread(td).start();
//這裡寫這個sleep()是為了讓CPU轉到目前線程來執行
try{Thread.sleep(1);}catch(Exception e){} td.str = "method";
new Thread(td).start();
//new Thread(td).start();
//new Thread(td).start();
}
}
這裡最關鍵的一點就是要想讓同步方法和同步代碼塊同步,兩者就要使用相同的螢幕對象
本程式中用的同一個螢幕對象是this