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--;
            }
        }
    }
}

  

原文地址:https://www.cnblogs.com/smartsmile/p/11605270.html