欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

传统线程同步

程序员文章站 2022-07-12 20:35:28
...
/**
 * 主线程和子线程轮流执行
 */
public class TraditionalThreadTest {
    public static void main(String[] args) {
        new TraditionalThreadTest().init();

    }

    public void init() {
        final Job job = new Job();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    job.sub();
                }
            }
        }).start();

        for (int i = 0; i < 10; i++) {
            job.main();
        }
    }


    class Job {
        private boolean flag = true;
        public synchronized void main() {
            if (!flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("main--------------------:i:" + i);
            }
            flag = false;
            this.notify();
        }

        public synchronized void sub() {
            if (flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("sub:i:" + i);
            }
            flag = true;
            this.notify();

        }
    }
}

 

相关标签: java thread