java 线程初探

来源:互联网 发布:淘宝秒杀抢拍器 编辑:程序博客网 时间:2024/05/21 09:58

本文主要探究主线程和子线程的执行顺序的。

通过2个类模拟,NewThread为子线程,RunnableDemo模拟主线程

public class NewThread implements Runnable {

    
/**
     * 
@param args
     
*/

    Thread t;

    
public NewThread() {
        t 
= new Thread(this"Child Thread");
        t.start();
        System.out.println(
"start child thread calls start()");
    }


    
public void run() {
        
// TODO 自动生成方法存根
        System.out.println("start child thread");
        
for (int i = 7; i > 0; i--{
            
try {
                System.out.println(
"child thread name is=" + t.getName() + "=="
                        
+ i);
                Thread.sleep(
500);
            }
 catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        System.out.println(
"child thread is ended");
    }


}

 

public class RunnableDemo {

    
/**
     * 
@param args
     
*/

    
public static void main(String[] args) {
        
// TODO 自动生成方法存根
        new NewThread();
        
        System.out.println(
"start main thread");

        
for(int i=7;i>0;i--){
            
try {
                System.out.println(
"main Thread=="+i);
                Thread.sleep(
1000);
            }
 catch (InterruptedException e) {
                
// TODO 自动生成 catch 块
                e.printStackTrace();
            }

        }

        System.out.println(
"main thread is ended");
    }


}

结果为

 

start child thread calls start()
start main thread
main Thread
==7
start child thread
child thread name is
=Child Thread==7
child thread name is
=Child Thread==6
main Thread
==6
child thread name is
=Child Thread==5
child thread name is
=Child Thread==4
main Thread
==5
child thread name is
=Child Thread==3
child thread name is
=Child Thread==2
main Thread
==4
child thread name is
=Child Thread==1
child thread is ended
main Thread
==3
main Thread
==2
main Thread
==1
main thread is ended

 

由上测试结果可见,子线程调用了start()后,并不会直接执行run(),而是先回到主线程,待主线程挂起时,才会

会到子线程继续执行。但有个较奇怪的问题是,如果在主线程中Thread.sleep(0),主线程仍然会挂起,而跳到子

线程去。

原创粉丝点击