我希望这段代码以一个二三,一二三等顺序运行线程但是它们以随机顺序运行我尝试了许多方法,比如设置优先级但似乎没有任何工作可以使所有三个线程以随机顺序运行,这是不是我想要的输出
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());
}
}
答案 0 :(得分:-1)
您只需维护一个线程序列来执行工作,并使其工作成为关键部分。一个关键部分是几行代码,一次只能运行一个线程但是在这里你想要一个线程的 STRICT SEQUENTIAL 模式,所以你只需要做它确定::
在for循环中,只有那个线程使用sequenceCount
变量执行转。有关更多说明,请参阅/ *注释* /内部代码。
class thrd extends Thread{
/* A sequence counter to make execution of threads sequentially */
static int sequenceCount=0;
Thread t;
public thrd(String name){
t=new Thread(this,name);
System.out.println(name+" Created");
}
@Override
public void run(){
try{
for(int i=0;i<5;i++){
/* Wait here if it is not current thread's turn */
while(true){
/* if it is 1st thread's turn and current thread is First Thread then break */
if((sequenceCount==0)&&(t.getName().equals("One")))break;
/* In this way other threads will wait it it is not their turn */
else if((sequenceCount==1)&&(t.getName().equals("Two")))break;
else if((sequenceCount==2)&&(t.getName().equals("Three")))break;
}
System.out.println(t.getName()+" : "+i);
Thread.sleep(500);
/* If it was last thread which printed out then move to 1st thread.. */
if(sequenceCount==2)sequenceCount=0;
/* OtherWise make it turn of next Thread */
else sequenceCount++;
}
}catch(Exception er){er.printStackTrace();}
}
}
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();
}
}