有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在用java编写一个代码来打印输出,如下所示

[精神]

[的]

[wipro]

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

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

我得到的结果如下:

[精神]

[wipro]

[的]


共 (2) 个答案

  1. # 2 楼答案

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

    这意味着您的案例中的所有线程都可以按任意顺序运行,这正是多线程的设计目的