当前位置: 首页 > 知识库问答 >
问题:

[使用交替线程交替打印]

房学
2023-03-14

我试图实现这一点:第一个线程打印1,第二个线程打印2,第三个线程打印3,第一个线程打印4等等:

我做到了这一点,并发挥了作用:

    class Display implements Runnable
    {
        int threadId;
        static int v=1;
        static int turn=1;//init
        static Object monitor=new Object();
        Display(int id)
        {
            this.threadId=id;   
        }
        public void run() {// TODO Auto-generated method stub
            print();
        }
        private void print() {
            // TODO Auto-generated method stub
            while(v<100)
            {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            synchronized(monitor)
            {
                if(threadId==1)
                {
                   if(turn!=1)
                   {
                      try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                   }
                   else
                   {
                       System.out.println(threadId + ":"+v);
                       v++;
                       turn=2;
                       monitor.notifyAll();
                   }
                }
                else if(threadId==2)
                {
                    if(turn!=2)
                       {
                          try { 
                            monitor.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                       }
                       else
                       {
                           System.out.println(threadId+":"+v);   
                           v++;
                           turn=3;
                           monitor.notifyAll();
                       }
                }
                else
                {
                    if(turn!=3)
                       {
                          try {
                            monitor.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                       }
                       else
                       {
                           System.out.println(threadId+":"+v); 
                           v++;
                           turn=1;
                           monitor.notifyAll();
                       }    

                }
            }
            }
        }
    }

    public class Print {

        public static void main(String[] ar)
        {       
        Thread t1= new Thread(new Display(1));
        Thread t2= new Thread(new Display(2));
        Thread t3= new Thread(new Display(3));
        t1.start();
        t2.start();
        t3.start();
        }
    }

输出是这样的:

1:1
2:2
3:3
1:4
2:5

它达到了目的,但是如果我有两个线程要打印,那么我必须使用更多的如果条件。

任何人都可以建议以更好的形式编写这段代码,以更干净的方式完成任务,这样如果添加更多线程,它就可以扩展。

共有1个答案

昌栋
2023-03-14

您需要给线程提供最高的id。之后,您可以使用模运算符简化代码。

class Display implements Runnable {
    int threadId;
    static int v = 1;
    static int higehstId = 0;
    static Object monitor = new Object();

    Display(int id) {
        this.threadId = id;
    }

    public void run() {
        print();
    }

    private void print() {
        while (v < 100) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            synchronized (monitor) {
                if ((v - 1) % higehstId == threadId - 1) {
                    System.out.println(threadId + ":" + v);
                    v++;
                    monitor.notifyAll();
                } else {
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    public static void main(String[] ar) {
        Thread t1 = new Thread(new Display(1));
        Thread t2 = new Thread(new Display(2));
        Thread t3 = new Thread(new Display(3));
        Thread t4 = new Thread(new Display(4));
        Thread t5 = new Thread(new Display(5));
        Display.higehstId = 5;
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

如果将v初始化为0,并开始从0为线程编号,则可以将If语句简化为:

if(v%high estId==threadId)

 类似资料:
  • 问题内容: 我一直在尝试解决涉及使用wait()和notify()的线程通信的问题。基本上我有2个线程T1和T2,我希望它们按以下顺序执行 T1,T2,T1,T2 .....我该如何实现? 实际的问题:有两个线程T1-打印奇数(例如1-100),而T2-打印偶数(1-100)。现在,输出应为1,2,3,4,5,.... 100 问题答案: 您描述了生产者-消费者模式。 它是Java的实现,在许多J

  • 我试图迭代一个分成块的切片,并返回一个元组,其中包含每个块的第n个元素。 示例:

  • 问题 你想通过数据集合动态的生成交替背景色的列表. 方案 Give templetor access to the int built-in and use modulo to test. code.py web.template.Template.globals['int'] = int template.html <ul> $var i: 0 $for track in tracks:

  • 这是我今天拍的日志: 你知道吗? 提前感谢!

  • 我有一个数组包含玩家的名字,我想按照数组的顺序显示每个问题中玩家的名字,例如arrnames['mark','john','jay'],我想和问题1的mark,问题2的john一起显示。 这是我正在尝试的,但我只得到数组中的最后一个值,我如何修复它?

  • 我有一个数组包含玩家的名字,我想按照数组的顺序显示每个问题中玩家的名字,例如arrnames['mark','john','jay'],我想和问题1的mark,问题2的john一起显示。 这是我正在尝试的,但我只得到数组中的最后一个值,我如何修复它?