Java-交替打印0-100

  1. 使用violate
    public class Main {
        private static volatile int flag = 1;
        public static void main(String[] args) {
            new Thread(()->{
                int i = 1;
                while(i < 100) {
                    if(flag == 1) {
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                        i += 2;
                        flag = 0;
                    }
                }
            }).start();
            new Thread(()->{
                int i = 2;
                while(i < 100) {
                    if(flag == 0) {
                        System.out.println(Thread.currentThread().getName() + ":" + i);
                        i += 2;
                        flag = 1;
                    }
                }
            }).start();
        }
    }
    

  2. 使用sychronized
    public class Main {
        public static void main(String[] args) {
            Thread1 thread = new Thread1();
            Thread thread1 = new Thread(thread);
            Thread thread2 = new Thread(thread);
            thread1.start();
            thread2.start();
        }
    }
    
    class Thread1 implements Runnable {
        int i = 0;
        @Override
        public void run() {
            while(i < 100) {
                synchronized (this) {
                    i++;
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                    notify();
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

 

你可能感兴趣的:(java,开发语言,算法)