对于给定的程序,您能否解释一下,因为我没有得到预期的结果:
package javaapplication14;
class Mythread implements Runnable{
String myname;
int myage;
public Mythread( String par_name, int par_age){
myname = par_name;
myage = par_age;
}
public void run(){
try{
for(int i=1; i<=myage; i++) {
System.out.println("Happy birthday "+myname);
Thread.sleep(2000);
}
}catch(Exception e){
System.out.println();
}
}
}
public class JavaApplication14 {
public static void main(String[] args) {
Mythread m = new Mythread("Mutinda ", 2);
Mythread p = new Mythread("Boniface", 2);
Thread k = new Thread(m);
Thread q = new Thread(p);
k.start();
q.start();
Thread t = new Thread(m);
try{
for( int i=1; i<=5; i++){
System.out.println("Main thread executing");
Thread.sleep(1000);
}
}catch(Exception e){
System.out.println("Thread interrupted");
}
}
}
这是我的输出:
Main thread executing
Happy birthday Boniface
Happy birthday Mutinda
Main thread executing
Main thread executing
Happy birthday Boniface
Happy birthday Mutinda
Main thread executing
Main thread executing
我期待这个:
Main thread executing
Happy birthday Mutinda
Happy birthday Boniface
Main thread executing
Main thread executing
Happy birthday Mutinda
Happy birthday Boniface
Main thread executing
Main thread executing
我需要有人向我解释为两个线程设置的优先级,k
并且无论睡眠时间如何,q
输出都q
成为第一个 than 。k
我的论点:因为在 ,k.start()
之前被调用q.start()
,所以期望我的输出以 开始k
,因为我首先调用它并且两者花费相同的睡眠时间。