1. 程式人生 > >網絡搶票synchronized同步票數(多線程,線程安全 )

網絡搶票synchronized同步票數(多線程,線程安全 )

package put -- ++ 編寫 style 代碼塊 lee 用戶

編寫

package com.Input_Output.I_O2;
    
/**
 *     車站搶票 同步代碼synchronized
 * @author zzh
 *
 */
public class Ticket {
    public static void main(String[] args) {
        //搶票的對象
        User u=new User();                //同一個線程
        Thread t1=new Thread(u,"小紅");
        Thread t2=new Thread(u,"小強");
        Thread t3
=new Thread(u,"黃牛"); t1.start(); t2.start(); t3.start(); } } /** * 搶票的用戶的線程 */ class User implements Runnable{ private int num; //搶到的第幾張票 private int count=20; //余票 /** * 搶票 */ public void run() {
while(true) { try { Thread.sleep(300); //模擬網絡延遲 } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this) { //同步代碼塊 一次只能有一個線程使用代碼塊 if
(count<=0) { break; } num++; count--; System.out.println(Thread.currentThread().getName()+"搶到了第"+num+"張票,還剩"+count+"張票"); if(Thread.currentThread().getName().equals("黃牛")) { return; } } } } }

運行

技術分享圖片

網絡搶票synchronized同步票數(多線程,線程安全 )