您的位置:首页 > 编程语言 > Java开发

Java 多线程售票案例(同步锁)

2018-03-12 16:25 429 查看
public class MyThread implements Runnable{
/**
* synchronized:同步锁: 保证资源同一时间 只能被同一条线程访问
* 可以锁对象
* 可以所方法
*/

int num = 100;//共100张票

@Override
public void run() {

//售票
while(num>0){

synchronized (this) {
num--;
if(num > 0){
System.out.println(Thread.currentThread().getName()+"售票一张,余票:"+num);
}else{
System.out.println("票售罄");
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

}

public class Test {
public static void main(String[] args){
MyThread mt = new MyThread();

Thread thread1 = new Thread(mt);
thread1.setName("窗口一");//重命名
thread1.start();

Thread thread2 = new Thread(mt);
thread2.setName("窗口二");
thread2.start();

Thread thread3 = new Thread(mt);
thread3.setName("窗口三");
thread3.start();

Thread thread4 = new Thread(mt);
thread4.setName("窗口四");
thread4.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: