diff --git a/javaSE-day05/src/com/inmind/thread07/MyThread.java b/javaSE-day05/src/com/inmind/thread07/MyThread.java index 3bf2383..7910c4b 100644 --- a/javaSE-day05/src/com/inmind/thread07/MyThread.java +++ b/javaSE-day05/src/com/inmind/thread07/MyThread.java @@ -1,16 +1,22 @@ package com.inmind.thread07; public class MyThread extends Thread{ + public MyThread(String name) { + super(name); + } //默认无参构造方法 - /*public MyThread(){ + public MyThread(){ super(); - }*/ + } @Override public void run() {//重写的run方法的作用:当前线程要执行的任务 - for (int i = 0; i < 1000; i++) { + /*for (int i = 0; i < 1000; i++) { System.out.println("hello pyhton"); - } + }*/ + + Thread subThread = Thread.currentThread(); + System.out.println("子线程的名字:"+subThread.getName()); } } diff --git a/javaSE-day05/src/com/inmind/thread07/ThreadDemo03.java b/javaSE-day05/src/com/inmind/thread07/ThreadDemo03.java new file mode 100644 index 0000000..26aed42 --- /dev/null +++ b/javaSE-day05/src/com/inmind/thread07/ThreadDemo03.java @@ -0,0 +1,42 @@ +package com.inmind.thread07; +/* + Thread类的常用API + + 构造方法: + 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 ThreadDemo03 { + public static void main(String[] args) { + //创建2个线程对象 + Thread thread1 = new MyThread("刘备"); + Thread thread2 = new MyThread("关羽"); + thread1.start(); + thread2.start(); + + System.out.println(thread1.getName()); + System.out.println(thread2.getName()); + + //在主方法中获取当前线程对象(主线程) + Thread mainThread = Thread.currentThread(); + System.out.println(mainThread.getName());//main + + //让主线程暂停2秒再执行 + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + //回顾:只有继承了RuntimeException的,在运行时才会报出的异常,是运行时异常 + //如果直接在编译时就报错错误的异常,就是编译时异常 + throw new RuntimeException(e); + } + + System.out.println("程序结束"); + } +}