作者H45 (!H45)
站内java
标题Re: [J2SE] Thread的执行
时间Thu Apr 3 15:13:50 2008
※ 引述《nf7series (真呆)》之铭言:
: 问个Thread执行的问题:
: public class ThreadTest extends Thread
: {
: public void run()
: {
: for(int i=0;i<11;i++)
: {
: System.out.println(getName()+":"+i);
: }
: }
: public static void main(String[] args) throws Exception
: {
: ThreadTest t1=new ThreadTest();
: ThreadTest t2=new ThreadTest();
: t1.start();
: t2.start();
: //t1.join();
: //Thread.sleep(1000);
: for(int i=0;i<11;i++)
: {
: System.out.println("Main Thread"+":"+i);
: }
: }
: }
: 以上的code,有两个建立出来的thread t1,t2和一个Main thread,各自都会印出0~10,
: 我刚测试,若code里面有用t1.join(),则t1一定会先跑完,才会再跑Main thread,但
: t1和t2仍是竞争的,没有说谁会比谁先执行完。
: 所以我是否可说join是用来确保thread会比Main thread先执行完的一种方法?
join 是等待另一个 thread 执行完。
: 另外,若我在程式中加入sleep()的方法,t1.sleep()、t2.sleep()、Thread.sleep()和
: sleep() <----没指定哪个thread,各是让哪个Thread休息呢?哪个thread呼叫sleep就是
: 让它自己休息吗?或是不管谁呼叫sleep都是让目前正在执行的thread休息?
sleep 是让呼叫者睡着,你会发现它是静态成员方法 (static member method)
: 先谢谢了~~
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.116.246.218