模拟火车站售票案例
同步代码块:
public class Ticket implements Runnable {
int tickets = 100;//总票数
Object obj = new Object(); //锁对象
@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;//总票数
Object obj = new Object(); //锁对象
@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--) + "张票");
}
}
}
测试类
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();
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。