利用Thread类的子类来创建线程

class MyThread extends Thread{  //创建Thread类的子类MyThread
    private String who;
    public MyThread(String str){ //构造方法,用于设置成员变量who
        who = str;
    }

    public void run(){  //覆盖Thread类的run()方法
        for(int i=0;i<5;i++){

            try {
                sleep((int)(1000*Math.random())); //sleep()方法必须写在try-catch块内
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(who+"正在运行!");
        }
    }
}

public class App11_1 {

    public static void main(String[] args) {
        MyThread you = new MyThread("你");
        MyThread she = new MyThread("她");
        you.start();
        she.start();

        System.out.println("主方法main()运行结束!");
    }
}

主方法main()运行结束!
你正在运行!
她正在运行!
你正在运行!
你正在运行!
她正在运行!
她正在运行!
你正在运行!
她正在运行!
她正在运行!
你正在运行!

Process finished with exit code 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值