栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

两个线程交替打印同一对象内0-100的奇数和偶数,使用synchronized,wait,notify。

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

两个线程交替打印同一对象内0-100的奇数和偶数,使用synchronized,wait,notify。

老杜java基础入门作业:两个线程对同一对象内的int类型数据交替输出奇数偶数。
import java.util.ArrayList;
import java.util.List;

public class HomeWorkJiaoTiShuChu {
    public static void main(String[] args){
        ShuChuZhi x = new ShuChuZhi();
        Thread c1= new Thread(new XianCheng1(x));
        Thread c2= new Thread(new XianCheng2(x));

        c1.setName("线程一奇数");
        c2.setName("线程二偶数");

        c1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        c2.start();

    }
}

class ShuChuZhi {
    private int i;

    public int getI() {
        return i;
    }

    public int addI(){
        return i++;
    }
}

class XianCheng1 implements Runnable{
    private ShuChuZhi i;

    public XianCheng1(ShuChuZhi i) {
        this.i = i;
    }

    @Override
    public void run() {
        while(i.getI()<100){
            synchronized (i){
                if(i.getI()%2==1){
                    System.out.println(Thread.currentThread().getName()+"输出"+i.addI());
                    i.notify();
                }
                else {
                    try {
                        i.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }
}

class XianCheng2 implements Runnable{
    private ShuChuZhi i;

    public XianCheng2(ShuChuZhi i) {
        this.i = i;
    }

    @Override
    public void run() {
        while(i.getI()<100){
            synchronized (i){
                if(i.getI()%2==0){
                    System.out.println(Thread.currentThread().getName()+"输出"+i.addI());
                    i.notify();
                }
                else {
                    try {
                        i.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }

        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781578.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号