zoukankan      html  css  js  c++  java
  • ABC三个线程,交替打印

          有三个线程,分别为A、B、C线程,需要线程交替打印:ABCABCABC...打印10次。

    首先创建一个一个线程间通讯的类:

    class Opt {
        //下一个执行的编号
        private Integer nextInde;
    
        public Integer getNextInde() {
            return nextInde;
        }
    
        public void setNextInde(Integer nextInde) {
            this.nextInde = nextInde;
        }
    }

    线程类:

    public class ABCThread extends Thread{
        //当前线程编号
        private Integer index;
        //线程通讯对象
        private Opt opt;
        //统计当前线程打印次数
        int num = 0;
        String[] thread = {"A","B","C"};
        public ABCThread(Integer index,Opt opt){
            this.index = index;
            this.opt = opt;
        }
    
        @Override
        public void run() {
            while (true) {
                synchronized (opt) {  //锁通信对象
                    while (opt.getNextInde() != index) { //循环  判断是否是当前线程执行(判断线程编号)
                        try {
                            //不是则等待
                            opt.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(thread[index]+" ");
                    num++;
                    //设置下一个执行线程编号
                    opt.setNextInde((index + 1) % 3);
                    //通知其他所有线程
                    opt.notifyAll();
                }
                if(num > 9) break;
            }
        }

    创建线程间通讯类的唯一对象,以及ABC三个线程:

     Opt opt = new Opt();
     opt.setNextInde(0);
     new ABCThread(0,opt).start();
     new ABCThread(1,opt).start();
     new ABCThread(2,opt).start();

  • 相关阅读:
    the Agiles Scrum Meeting 8
    the Agiles Scrum Meeting 7
    the Agiles Scrum Meeting 6
    项目使用说明——英文版
    第十次例会
    第九次例会
    第八次例会
    第六次例会
    第七次例会
    第五次例会
  • 原文地址:https://www.cnblogs.com/128-cdy/p/12552306.html
Copyright © 2011-2022 走看看