s-day05--多线程的实现方式一继承thread的原理与常用方法
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
package com.inmind.thread01;
|
||||
/*
|
||||
构造方法:
|
||||
public Thread() :分配一个新的线程对象。
|
||||
public Thread(String name) :分配一个指定名字的新的线程对象。
|
||||
|
||||
常用方法:
|
||||
public String getName() :获取当前线程名称。
|
||||
public void start() :导致此线程开始执行; Java虚拟机调用此线程的run方法。
|
||||
public void run() :此线程要执行的任务在此处定义代码。
|
||||
public static void sleep(long millis) :使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行)。
|
||||
public static Thread currentThread() :获取到当前正在执行的线程对象。(重点)
|
||||
*/
|
||||
public class Demo01 {
|
||||
public static void main(String[] args) {
|
||||
//创建2个线程对象,如果不起名字,线程默认起名:thread-0,1,2....
|
||||
MyThread thread1 = new MyThread("刘备");
|
||||
MyThread thread2 = new MyThread("关羽");
|
||||
//启动2个线程
|
||||
thread1.start();
|
||||
thread2.start();
|
||||
|
||||
// System.out.println(thread1.getName());
|
||||
// System.out.println(thread2.getName());
|
||||
|
||||
Thread mainThread = Thread.currentThread();//获取main方法所在的线程对象
|
||||
System.out.println("main方法所在的线程名:"+mainThread.getName());
|
||||
|
||||
//让主线程睡一会
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println("处理了一个线程终止的异常");
|
||||
}
|
||||
System.out.println("程序结束");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.inmind.thread01;
|
||||
|
||||
//线程类
|
||||
public class MyThread extends Thread {
|
||||
|
||||
public MyThread() {
|
||||
}
|
||||
|
||||
public MyThread(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
Thread subThread = Thread.currentThread();
|
||||
System.out.println(subThread.getName()+"子线程执行了");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user