/***
- 除了可以對代碼塊進行同步外澈吨。也可以對方法進行方法同步
- @author bo
*/
public class ThreadMet {
public static void main(String[] args) {
TestThreadM threadM = new TestThreadM();
Thread thread = new Thread(threadM);
//開啟多線程
thread.start();
}
}
class TestThreadM implements Runnable{
private int tickets = 20;
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
saleTicket();
}
}
public synchronized void saleTicket() {//synchronized方法來實現(xiàn)同步....
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
System.out.println(Thread.currentThread().getName() + "當前的票" +tickets--);
}
}
}
使用synchonized方法來實現(xiàn)線程之間的同步谷朝,當有一個線程進入到synchonized方法修飾的方法中的時候惑惶,其他的線程并不能進入此方法區(qū)域,直到第一個線程執(zhí)行完成并且離開后凄吏,釋放了它的響應權远舅。其他線程才能進入到此區(qū)域..