多线程中不需要的输出 [英] unwanted output in multithreading

查看:103
本文介绍了多线程中不需要的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class mythread implements Runnable {

    Thread t1;
    String name = "";

    public mythread(String thname) {
         name = thname;
         t1= new Thread(this, name);
         System.out.println(t1);
         t1.start();
         System.out.println(t1.getName());
     }
     @Override
     public void run() {
         for (int i=5;i>0;i--){
             try {
                System.out.println(Thread.currentThread());
                 System.out.println("child Thread" + i);
                 Thread.sleep(2000);
             }  catch(InterruptedException e){
                System.out.println("Child Thread Interrupted");
             }
         }
     }
}

public class Mainthread {
   public static void main(String[] args) {
        mythread m1 = new mythread("Rohan");
        mythread m2 = new  mythread("Jain");

        try {
            for(int i=5;i>0;i--){
                System.out.println("Main Thread" + i);
                 Thread.sleep(2000);
            }
        } catch(InterruptedException e){
            System.out.println("Main Thread Interrupted");
        }
    }
}

输出结果为:

Thread[Rohan,5,main]
Rohan
Thread[Jain,5,main]
Thread[Rohan,5,main]
child Thread5
Jain
Main Thread5
Thread[Jain,5,main]
child Thread5
Main Thread4
Thread[Rohan,5,main]
child Thread4
Thread[Jain,5,main]
child Thread4
Main Thread3
Thread[Rohan,5,main]
child Thread3
Thread[Jain,5,main]
child Thread3
Main Thread2
Thread[Jain,5,main]
Thread[Rohan,5,main]
child Thread2
child Thread2
Thread[Rohan,5,main]
child Thread1
Thread[Jain,5,main]
child Thread1
Main Thread1

但我想要的输出就像第一个它应该打印5个线程rohan然后5个线程中的jain然后5个线程main等等...请帮助.. !!!!!!

but the output i want is like first it should print the 5 in thread "rohan" then 5 in thread in "jain" then 5 in thread "main" and so on...please help..!!!!!!

推荐答案

这些问题让我很困惑。线程的全部意义在于它们并行运行异步,因此我们获得了更好的性能。由于硬件,竞争条件,时间切片随机性和其他因素,无法预测线程运行的顺序。任何询问线程程序中特定输出顺序的人都不应该使用线程。

These sort of questions really confuse me. The whole point of threads is that they run asynchronously in parallel so we get better performance. The order that threads run cannot be predicted due to hardware, race-conditions, time-slicing randomness, and other factors. Anyone who is asking about specific order of output in a threaded program should not be using threads at all.

以下是对同一问题的类似答案:

Here are similar answers to the same question:

如何获取我的线程程序打印特定输出

为什么输出每次都不同而不是同步块

多线程Hel lo世界

这篇关于多线程中不需要的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆