java 线程初探

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

通过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),主线程仍然会挂起,而跳到子

线程去。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值