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

共享内存(不使用锁)

class test {

    private static int count = 0;

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

    private static class MyThread extends Thread {
        private final int id;

        private MyThread(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++;
                    }
                }
            }
        }
    }
}
posted @ 2023-05-09 22:07  你在学什么  阅读(67)  评论(0)    收藏  举报