构建Thread子类对象

Java直接定义了一个从根类Object中派生的Thread类。所以从java.lang.Thread类派生的直接子类或间接子类均为线程。构建Thread子类对象的步骤如下:

①构建Thread子类,重写其中的run()方法。

②创建线程对象。

③线程对象调用start()方法启动该线程。

代码示例:

public class Example11_1 extends Thread{
    String threadId;
    Example11_1(String threadId){
        this.threadId=threadId;
    }
    public void run(){
        System.out.println("Thread started:"+this.threadId);
        for (int i = 0; i < 6; i++) {
            System.out.print("i="+(i+1)+"\t");
        }
        System.out.println("Thread stooped:"+this.threadId);
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        System.out.println("Starting ThreadTest1");
        Example11_1 t1=new Example11_1("thread1");
        t1.start();
        System.out.println("Starting ThreadTest2");
        Example11_1 t2=new Example11_1("thread2");
        t2.start();
        System.out.println("Starting ThreadTest3");
        Example11_1 t3=new Example11_1("thread3");
        t3.start();
        System.out.println("end");
    }
}

某次运行图:

 每次运行时可能不一样。

代码分析:

在ThreadTest类中不止有3个线程,至少有4个线程。其中3个线程在main()方法里面创建,还有一个线程执行main()方法。main()方法启动后,建立一个线程实例,在3个子线程获得执行之前完成自己的工作。

因此

Starting ThreadTest1
Starting ThreadTest2
Starting ThreadTest3
end

语句总是在最前面。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值