Java 多線程示例


/**
 * 多線程案例 兩種方式  模擬買票程序(不考慮線程安全問題)
 */
public class ThreadTest {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + " main run start");

        //方式1
        /**
         * 模擬4個售票窗口售票
         */
        // Ticket test1 = new Ticket();
        // Ticket test2 = new Ticket();
        // Ticket test3 = new Ticket();
        // Ticket test4 = new Ticket();
        // test1.start();
        // test2.start();
        // test3.start();
        // test4.start();

        //方式2
        TestImpl ti1 = new TestImpl();
        TestImpl ti2 = new TestImpl();
        TestImpl ti3 = new TestImpl();
        TestImpl ti4 = new TestImpl();
        new Thread(ti1).start();
        new Thread(ti2).start();
        new Thread(ti3).start();
        new Thread(ti4).start();


        System.out.println(Thread.currentThread().getName() + " main run finished");
    }
}

/**
 * 方式1 繼承Thread類重寫run方法
 */
class Ticket extends Thread {
    private static int ticketCount = 100;

    @Override
    public void run() {
        while (ticketCount > 0) {
            System.out.println(Thread.currentThread().getName() + " extends run tickNum" + ticketCount--);
        }
    }
}

/**
 * 方式1 實現Runnable接口
 */
class TestImpl implements Runnable {
    private Object obj = new Object();
    private static int ticketCount = 100;

    @Override
    public void run() {
        while (ticketCount > 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            sale();
        }
    }

    /**
     * 使用同步代碼塊解決多線程安全問題
     */
    public void sale() {
        synchronized (this) {
            if (ticketCount > 0) {
                System.out.println(Thread.currentThread().getName() + "還剩" + (ticketCount) + "張票");
                ticketCount--;
            }
        }
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM