使用线程无法按预期获得输出

时间:2013-05-20 18:22:49

标签: java multithreading

我在java中编写代码以打印输出,如下所示

[精神]

[的]

[威普罗]

但是我在设置线程的优先级时遇到了问题,并且看到每个线程都是priorty并且没有按预期获得输出。

  class shobj
  {
   public synchronized void  sharedMethod(String arg)
    { 
  System.out.print("[");
  System.out.print(arg);
  try 
     { 

      Thread.sleep(1000);
     }
    catch(Exception e)
    {
     System.out.println("INTERRUPTED");
    }
    System.out.println("]");
  }
}
  class thread1 implements Runnable
 {
  String arg;
  shobj obj1;
  Thread t;
  public thread1(shobj obj1,String arg)
     {
      this.obj1=obj1;
      this.arg=arg;
      t=new Thread(this);
      t.start();
//    System.out.println(t.currentThread());
      }
  public void run()
       {
        obj1.sharedMethod(arg);
        }
}

 class synchro

   {

  public static void main(String args[])
 {
  shobj ob = new shobj();
  thread1 x1 = new thread1(ob,"spirit");
  thread1 x2 = new thread1(ob,"of");
  thread1 x3 = new thread1(ob,"wipro");
  x3.t.setPriority(Thread.NORM_PRIORITY+3);
  x2.t.setPriority(Thread.NORM_PRIORITY+2);
  x1.t.setPriority(Thread.NORM_PRIORITY+1);


  try
     {
      x1.t.join(); //System.out.println(x1.t.currentThread());
      x2.t.join();//System.out.println(x2.t.currentThread());
      x3.t.join();//System.out.println(x3.t.currentThread());
      }
    catch(Exception e)
     {
    System.out.println("Interruted Exception");
     }
      }
   }     

我的输出如下:

[精神]

[威普罗]

[的]

2 个答案:

答案 0 :(得分:1)

请参阅How are Java Thread priorities translated to an OS thread priority?线程优先级如何映射到本机操作系统。无法保证java中不同的线程优先级会导致操作系统级别的优先级不同。

答案 1 :(得分:0)

优先级只是对操作系统的暗示。如果你有足够的空闲CPU,那么想要运行的所有线程都可以运行。

这意味着你的案例中的所有线程都可以以任何顺序运行,这就是设计多个线程的目的。