1
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

但我想要的输出就像首先它应该在线程“rohan”中打印 5,然后在“jain”中的线程中打印 5,然后在线程“main”中打印 5,依此类推......请帮助..!!!!!!

4

3 回答 3

8

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:

于 2013-07-23T16:48:19.063 回答
2

您可能希望在单个对象上使用锁来控制排序。有关详细信息,请参阅Java 线程锁教程

于 2013-07-23T16:42:44.003 回答
0

线程被赋予处理器时间或在操作系统级别调度。因此,您的程序无法直接控制指令在其自己的线程中执行的时间。所以现在有订单保证。有一些特定于操作系统的变量会进入调度。

如果您想保证跨线程的顺序,那么您的线程需要进行通信。有几种方法可以做到这一点。最常见的程序员使用互斥锁。这也称为锁。

于 2013-07-23T16:56:24.733 回答