您好,登錄后才能下訂單哦!
模擬火車站售票案例
同步代碼塊:
public class Ticket implements Runnable {
int tickets = 100;//總票數(shù)
Object obj = new Object(); //鎖對(duì)象
@Override
public void run() {
//賣票
while (true) {
synchronized (obj) {
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "賣出了第" + (tickets--) + "張票");
}
}
}
}
}
同步方法
public class Ticket implements Runnable {
int tickets = 100;//總票數(shù)
Object obj = new Object(); //鎖對(duì)象
@Override
public void run() {
//賣票
while (true) {
method();
}
}
public synchronized void method(){
if (tickets > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "賣出了第" + (tickets--) + "張票");
}
}
}
測(cè)試類
public class TicketTest {
public static void main(String args[]){
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
t1.setName("窗口1");
t2.setName("窗口2");
t3.setName("窗口3");
t1.start();
t2.start();
t3.start();
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。