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();

}






}

你可能感兴趣的:(Java,Thread)