import java.io.*;public class MyThread implements Runnable{ public void run(){ System.out.println("hello");
System.out.println(Thread.currentThread().getName());
} public static void main(String args[]) {
try{
MyThread mythread = new MyThread();
Thread thread1 = new Thread(mythread); Thread thread2 = new Thread("hello");
thread1.run();
thread2.run();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
我怎么能让thread1,thread2能有不同的输出?为什么Thread.currentThread().getName()输出的总是main?
System.out.println(Thread.currentThread().getName());
} public static void main(String args[]) {
try{
MyThread mythread = new MyThread();
Thread thread1 = new Thread(mythread); Thread thread2 = new Thread("hello");
thread1.run();
thread2.run();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}
我怎么能让thread1,thread2能有不同的输出?为什么Thread.currentThread().getName()输出的总是main?
别用thread.run()
用 thread.start()
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. 这是文档里说的,哪位给解释一下?
import java.io.*;public class MyThread implements Runnable{ public void run(){ System.out.println("hello");
System.out.println(Thread.currentThread().getName());
} public static void main(String args[]) {
try{
MyThread mythread = new MyThread();
Thread thread1 = new Thread(mythread); Thread thread2 = new Thread(mythread);
thread1.run();
thread2.run();
}
catch(Exception e){
System.out.println(e.toString());
}
}
}中的 thread1.run();
thread2.run();如果改为 thread1.start();
thread2.start();结果不一样,线程名字打印的不一样啊,
大家可以试一下,然后解释原因。
我认为
调用run的话就相当于直接在main线程里头调用一个很一般的method,和其它语句没有什么两样,等到这条语句调用结束之后接着调用下一条语句,是顺序执行的,并且都在main线程里头。但是
如果调用start就不同了,他是thread的一个独特的方法,JVM会把这个线程直接放到准备就绪的线程队列中,让操作系统去调度它,然后返回了。这样,才是真正的多线程。
而操作系统调度到了这个线程,就会主动去执行它的run方法。当然,问题的关键是操作系统什么时候去调度它,这个和各个不同操作系统的线程调度策略有关了,和java没有什么关系(不过你还是可以为每个线程设定优先级的)。
因此我们可以认为,在这种情况下,thread1和thread2的run方法的调用顺序和结束顺序是不可知的。(当然,除非你使用了线程的同步方法) 通过和第一中情况比较我们可以画出他们的运行关系图
A:
in main thread
-> thread1.run start-->thread1.run over-->thread2.run start->thread2.run over--> go on other after these code
B:
in main thread
->send thread1 to thread queue->send thread2->go on other after these code
in thread1 thread
-> thread1.run start-->thread1.run over
in thread2 thread
-> thread2.run start-->thread2.run over以上是个人看法,欢迎讨论
我觉得
在那个System.out.println(Thread.currentThread().getName());
后面加上
System.out.println("hello over" + i++);
这一句
在看看
run和start的结果就知道了