我希望此代碼運行順序一二三,一二三等,但他們運行在隨機順序我嘗試過很多辦法,如設置優先級,但似乎沒有任何工作以隨機順序運行所有三個線程這不是我想要的輸出我想線程工作的順序創造,但我不能這樣做使用此代碼的建議,請
class thrd extends Thread
{
Thread t;
thrd(String name)
{
t=new Thread(this,name);
System.out.println(name +":Created"+t);
}
@Override
public void run(){
try
{
for(int i=1;i<=5;i++)
{
System.out.println(t.getName()+": "+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("Interrupted"+e);
}
}
}
public class threadse {
public static void main(String[] args)
{
thrd o1=new thrd("One");
thrd o2=new thrd("Two");
thrd o3=new thrd("Three");
o1.t.start();
o2.t.start();
o3.t.start();
System.out.println("Thread One alive: "+o1.t.isAlive());
System.out.println("Thread Two alive: "+o2.t.isAlive());
System.out.println("Thread Three alive: "+o3.t.isAlive());
try
{
System.out.println("Waiting");
o1.t.join();
o2.t.join();
o3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted: "+e);
}
System.out.println("Thread one alive: "+o1.t.isAlive());
System.out.println("Thread Two alive: "+o2.t.isAlive());
System.out.println("Thread Three alive: "+o3.t.isAlive());
}
}
線程的重點本質上是它們獨立運行。如果你想按照某個順序完成某些操作 - 「做Foo,酒吧,然後Baz」 - 那麼最簡單的方法就是在一個線程上運行它們。 – yshavit
這不是線程的工作方式。如果你想順序執行使用單個線程。否則,你需要使用幾種機制之一來控制線程的執行,但是這太寬泛了,不能在這裏回答(但你可以通過搜索找到大量的例子)。 – Kayaman
感謝您的幫助 – VIPER