两个线程交替打印100以内的数字

发布时间 2023-05-09 22:13:06作者: 你在学什么

共享内存

class test {

    private static int count = 0; // 共享的计数器

    public static void main(String[] args) {
        Thread t1 = new Thread(new Printer(0));
        Thread t2 = new Thread(new Printer(1));
        t1.start();
        t2.start();
    }

    private static class Printer implements Runnable {
        private final int id;

        public Printer(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            while (count < 100) {
                synchronized (this) {
                    if (count % 2 == id) {
                        System.out.println(Thread.currentThread().getName() + ": " + count);
                        count++;
                    }
                }
            }
        }
    }
}