Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

java - unwanted output in multithreading

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");
        }
    }
}

The output is:

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

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..!!!!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...