首页 > 编程语言 > 详细

两个线程交替打印1到100

时间:2017-11-26 11:59:25      阅读:689      评论:0      收藏:0      [点我收藏+]
package com.zs.thread;

import java.util.concurrent.TimeUnit;

public class SumThread {
    
    public void one() throws InterruptedException{
        synchronized (this) {
            boolean flag = true;
            
            while (flag) {
                
                for(int i = 1; i <= 99;i += 2){
                    System.out.println(i);
                    
                    if(i==99){
                        flag = false;
                        this.notify();
                        break;
                    }
                    this.notify();
                    this.wait();
                }
            }
        }
    }   
        
    public void two() throws InterruptedException{
            synchronized (this) {
                boolean flag = true;
                
                while (flag) {
                    
                    for(int i = 2; i <= 100;i += 2){
                        System.out.println(i);
                        
                        if(i==100){
                            flag = false;
                            this.notify();
                            break;
                        }
                        this.notify();
                        this.wait();
                    }
                }
            }
        }
        
        
    
    public static void main(String[] args) throws Exception {
        SumThread sumThread = new SumThread();
        
        new Thread(()->{
            try {
                sumThread.one();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        
        TimeUnit.SECONDS.sleep(1);
        
        new Thread(()->{
            try {
                sumThread.two();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

两个线程交替打印1到100

原文:http://www.cnblogs.com/leihuazhe/p/7898563.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!