三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示

一、如图

在这里插入图片描述
ABCABCMain.java

package PrintABC;

public class ABCABCMain {
    public static void main(String[] args) {
        ThreadName threadName = new ThreadName();
        threadName.setIndex(0);
        Thread thread0 = new Thread(new ThreadDemo(0, threadName));
        Thread thread1 = new Thread(new ThreadDemo(1,threadName));
        Thread thread2 = new Thread(new ThreadDemo(2,threadName));
        thread0.setName("A");
        thread1.setName("B");
        thread2.setName("C");
        thread0.start();
        thread1.start();
        thread2.start();

    }
}

ThreadDemo.java

package PrintABC;

public class ThreadDemo extends Thread {
    private Integer threadNum;//当前线程编号
    private ThreadName threadName;//线程间传递对象
    public ThreadDemo(Integer threadNum, ThreadName threadName){
        this.threadName = threadName;
        this.threadNum = threadNum;
    }

    @Override
    public void run() {
        int i = 1;
        while (i <= 10) {
            synchronized (threadName) {
                while (threadNum != threadName.getIndex()) {
                    try {
                        threadName.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(Thread.currentThread().getName());
                threadName.setIndex((threadNum+1)%3);
                threadName.notifyAll();
                i++;
            }
        }

    }
}

ThreadName.java

package PrintABC;

public class ThreadName {
    private Integer index;//当前执行线程ID
    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }
}

运行结果:

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值