美文网首页
多线程交替打印从0~100

多线程交替打印从0~100

作者: 小飞剑客 | 来源:发表于2021-02-04 17:48 被阅读0次

    简单粗暴直接上代码。

    public class ThreadTest2 {
    
        public synchronized void increateNum(int count) {
            try {
                this.notify();
                System.out.println(Thread.currentThread().getName()+"="+ count);
                this.wait();
            } catch (Exception e) {
    
            }
        }
        public static void main(String[] args) throws InterruptedException {
            CountDownLatch countDownLatch = new CountDownLatch(100);
            ThreadTest2 threadTest2 = new ThreadTest2();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 100; i+=2) {
                        countDownLatch.countDown();
                        threadTest2.increateNum(i+1);
                    }
    
                }
            });
            thread.setName("thread1");
            thread.start();
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 1; i < 100; i+=2) {
                        countDownLatch.countDown();
                        threadTest2.increateNum(i+1);
                    }
                }
            });
            thread1.setName("thread2");
            thread1.start();
    
            countDownLatch.await();
            System.out.println("--两个线程执行完毕--");
    
            thread.interrupt();
            thread1.interrupt();
            System.out.println("———终止所有线程——");
        }
    }
    

    相关文章

      网友评论

          本文标题:多线程交替打印从0~100

          本文链接:https://www.haomeiwen.com/subject/mxdgtltx.html