线程安全问题(使用同步函数)

来源:互联网 发布:zipfor mac中文破解版 编辑:程序博客网 时间:2024/06/05 16:20
class SaleTicket2 extends Thread {static int num = 5000;// 票数,静态共享变量static Object o = new Object();// 同步对象public SaleTicket2(String name) {// 获取名字super(name);}// 重写run方法// 同步函数public void run() {// 死循环get();}public static synchronized void get() {while (true) {// 同步代码块// synchronized (o) {if (num > 0) {num -= 1000;System.out.println(Thread.currentThread().getName()+ "取了1000还剩" + num);try {Thread.sleep(100);// 休眠100毫秒} catch (Exception e) {e.printStackTrace();}} else {System.out.println("取光了");break;// 跳出循环}// }}}}public class ThreadSecurity2 {public static void main(String[] args) {Thread t1 = new SaleTicket2("老公");Thread t2 = new SaleTicket2("老婆");t1.start();t2.start();}}



阅读全文
0 0
原创粉丝点击