多线程打印连续数字,例如 1,2,3,4,5......

public class MultiThread extends Thread {

    /**
     * 使用内部类,线程对x是无感知的,只有 Factory 知道x 的变化。这样就避免了x变化,
     * 而其它线程没有读取到变化后的值,即避免了读脏数据的问题
     */
    private static class Factory{
        private static int x = 0;
        private static synchronized void printNum() {
            System.out.println(Thread.currentThread().getName() + ": " + x);
            x ++;
        }
    }

    private MultiThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i ++) {
            Factory.printNum();
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new MultiThread("t1");
        Thread thread2 = new MultiThread("t2");
        Thread thread3 = new MultiThread("t3");

        thread1.start();
        thread2.start();
        thread3.start();
    }

 

你可能感兴趣的:(多线程打印连续数字,例如 1,2,3,4,5......)