thread_create(线程基本常识)

package com.gzhs.zsd.thread;






/***
 * 了解线程创建方式
 * 线程Thread实现Runnable接口
 * @author 谢泽鹏
 * @version 1.0
 */
public class Traditional_Thread {





public static void main(String[] args) {

//方式一
//线程类Thread创建, 启动时调用父类的run()方法.
Thread thread_01 = new Thread();
thread_01.start();
System.out.println("thread_01 线程编号: " + thread_01.getName() + " #### " + "thread_01 线程名称: " + thread_01.getId());


//方式二
//线程类Thread创建, 启动时重写父类的run()方法. 调用时super.run();表示先调用父类run()方法
Thread thread_02 = new Thread(){
@Override
public void run() {
while (true) {
try {
//线程睡眠5秒
Thread.sleep(5000);
//这里this指的是当前线程对象,即 thread_02, 所以这里可以采用this.getName()和this.getId()获取线程名称。
System.out.println("thread_02 线程编号:  " + this.getName() + " #### " + "thread_02 线程名称: " + this.getId());
System.out.println("thread_02 线程编号:  " + Thread.currentThread().getName() + " #### " + "thread_02 线程名称: " + Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread_02.start();


//方式三
//线程类Thread创建, 启动时重写Runnable的run()方法
Thread thread_03 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
//线程睡眠5秒
Thread.sleep(5000);
//这里this指的是当前Runnable的对象,所以这里无法调用this.getName()和this.getId()获取线程名称。
//System.out.println("thread_02 线程编号:  " + this.getName() + " #### " + "thread_02 线程名称: " + this.getId());
System.out.println("thread_02 线程编号:  " + Thread.currentThread().getName() + " #### " + "thread_02 线程名称: " + Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
});
thread_03.start();



//方式四
//线程类Thread创建, 如创建线程时即实现写Thread的run(), 又实现Runnable的run()方法时。
//Thread的run会执行, 覆盖Runnable的run()方法, 其中Runnable的run()方法不会执行. 形式未new Thread(new runnable){run}
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
//线程睡眠5秒
Thread.sleep(5000);
System.out.println("执行Runnable里面run方法 线程编号:  " + Thread.currentThread().getName() + " #### " + " 线程名称: " + Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}){
public void run() {
while (true) {
try {
//线程睡眠5秒
Thread.sleep(5000);
System.out.println("执行Thread里面run方法  线程编号:  " + Thread.currentThread().getName() + " #### " + " 线程名称: " + Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}

};
}.start();

}






}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

suenpeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值