线程安全问题(使用同步代码块)

来源:互联网 发布:js string长度 编辑:程序博客网 时间:2024/05/29 16:22
class SaleTicket extends Thread {static int num = 50;// 票数,静态共享变量static Object o = new Object();// 同步对象public SaleTicket(String name) {// 获取名字super(name);}// 重写run方法public void run() {// 死循环while (true) {// 同步代码块synchronized (o) {if (num > 0) {System.out.println(Thread.currentThread().getName()+ "售出了第" + num + "张票");num--;try {Thread.sleep(100);// 休眠100毫秒} catch (Exception e) {e.printStackTrace();}} else {System.out.println("卖完了");break;// 跳出循环}}}}}public class ThreadSecurity {public static void main(String[] args) {Thread t1=new SaleTicket("窗口1");Thread t2=new SaleTicket("窗口2");t1.start();t2.start();}}



阅读全文
0 0