我这个用到了join()方法但为什么结果还是“我正在运行”与“他正在运行”?为什么会出现这个问题。我想先把“我正在运行”打印完后再打印“他正在运行”。我知道在m.start();后直接写try{me.join();——可以实现。但我就是不理解这是什么原因。望各位大虾指点。
epublic class myThread2 implements Runnable { private String who;
public myThread2(String str) {
who = str;
}
public void run() {
for(int i = 1;i<=5;i++){
try{
Thread.sleep((int)(1000*Math.random()));
}catch(InterruptedException e){}
System.out.println(who+"正在运行!");
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
myThread2 m1 = new myThread2("我");
myThread2 t1 = new myThread2("他");
Thread me = new Thread(m1);
Thread he = new Thread(t1);
me.start();
he.start(); try{
me.join();
}catch(InterruptedException e){
e.toString();
}
try{
he.join();
}catch(InterruptedException e){}
System.out.println("主方法结束!"); }}
epublic class myThread2 implements Runnable { private String who;
public myThread2(String str) {
who = str;
}
public void run() {
for(int i = 1;i<=5;i++){
try{
Thread.sleep((int)(1000*Math.random()));
}catch(InterruptedException e){}
System.out.println(who+"正在运行!");
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
myThread2 m1 = new myThread2("我");
myThread2 t1 = new myThread2("他");
Thread me = new Thread(m1);
Thread he = new Thread(t1);
me.start();
he.start(); try{
me.join();
}catch(InterruptedException e){
e.toString();
}
try{
he.join();
}catch(InterruptedException e){}
System.out.println("主方法结束!"); }}
要想先把“我正在运行”打印完后再打印“他正在运行”。就应该在执行“我正在运行”时将“他正在运行”挂起,执行完“我正在运行”时再唤醒“他正在运行”线程。
public class JoinThread implements Runnable {
private String who;
public JoinThread(String str) {
who = str;
}
public void run() {
synchronized (JoinThread.class) {
for(int i = 1;i<=5;i++){
try{
Thread.sleep((int)(1000*Math.random()));
}catch(InterruptedException e){}
System.out.println(who+"正在运行!");
}
}
}
public static void main(String[] args) {
JoinThread m1 = new JoinThread("我");
JoinThread t1 = new JoinThread("他");
Thread me = new Thread(m1);
Thread he = new Thread(t1);
me.start();
he.start();
System.out.println("主方法结束!");
}
}
楼主的程序,是main线程调用了me.join(). 那就是main线程暂不执行,直到me线程结束后,main再接着执行。
那么就是me和he两个线程在执行。(被虚拟机以用样的机会调度)。出现的结果是不确定的。一般是me 和he 交替 的执行。
// TODO Auto-generated method stub
myThread2 m1 = new myThread2("我");
myThread2 t1 = new myThread2("他");
Thread me = new Thread(m1);
Thread he = new Thread(t1);
me.start();
try{
me.join();
}catch(InterruptedException e){
e.toString();
}
he.start();
try{
he.join();
}catch(InterruptedException e){}
System.out.println("主方法结束!"); }