多线程:两个线程交替打印奇偶数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenpengjia006/article/details/81943316

嗯,比较简单的小东西,添加了任务完成退出的处理。

/***
 * 要求:两个线程交替打印从1到100的数字。
 */
public class PrintSD {

    //定义打印的方法
    public synchronized void print(String str,int num){
        notify();
        System.out.println(str+num);
        try {
            if(100 != num){
                wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //奇数打印线程
    class Odd implements Runnable{
        @Override
        public void run() {
            for(int i=1;i<100;i+=2){
                print("奇数:",i);
            }
        }
    }

    //偶数打印线程
    class Even implements Runnable{
        @Override
        public void run() {
            for(int i=2;i<=100;i+=2){
                print("偶数:",i);
            }
        }
    }

    public static void main(String[] args) {
        PrintSD p = new PrintSD();
        Odd odd = p.new Odd();
        Even even = p.new Even();
        new Thread(odd).start();
        new Thread(even).start();
    }
}

猜你喜欢

转载自blog.csdn.net/chenpengjia006/article/details/81943316