我用Java編寫代碼來打印輸出如下使用線程無法得到輸出如預期
[精神]
[中]
[Wipro公司]
但我在設置線程的優先級並看到每個線程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");
}
}
}
我得到的輸出如下:
[精神]
[Wipro公司]
[中]
你得到的輸出是什麼?什麼會讓你覺得你會得到上面的輸出?僅僅因爲一個線程具有更高的優先級並不意味着其他線程不會運行(特別是在多處理器的機器上)。 –
鑑於你的代碼,我會期望:'[sprit [wipro]]]或者它的一些變化,特別是考慮到線程已經開始之前,你設置他們的優先事項。 –
設置線程優先級只是一個提示,它是在JVM和處理器上承諾的那些 –