From 284d5762c5348dd49aca2b031f600725027139d2 Mon Sep 17 00:00:00 2001 From: xuxin <840198532@qq.com> Date: Wed, 5 Aug 2026 16:12:46 +0800 Subject: [PATCH] =?UTF-8?q?s-day05-Thread=E9=87=8C=E9=9D=A2=E5=B8=B8?= =?UTF-8?q?=E8=A7=81=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- s-day06/src/com/inmind/thread01/Demo01.java | 44 +++++++++++++++++++ s-day06/src/com/inmind/thread01/MyThread.java | 19 ++++++++ 2 files changed, 63 insertions(+) create mode 100644 s-day06/src/com/inmind/thread01/Demo01.java create mode 100644 s-day06/src/com/inmind/thread01/MyThread.java diff --git a/s-day06/src/com/inmind/thread01/Demo01.java b/s-day06/src/com/inmind/thread01/Demo01.java new file mode 100644 index 0000000..598ed4d --- /dev/null +++ b/s-day06/src/com/inmind/thread01/Demo01.java @@ -0,0 +1,44 @@ +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) throws InterruptedException { + /* + public Thread() :分配一个新的线程对象。 + Thread-0-1-2:无参构造的线程名称 + */ + /* + public Thread(String name) :分配一个指定名字的新的线程对象。 + 可以通过构造方法设置线程的名称 + */ + MyThread myThread1 = new MyThread("刘备"); + MyThread myThread2 = new MyThread("关羽"); + //myThread1.run();//run方法一定不能主动调用,只能通过start方法启动线程,让线程执行run方法 + myThread1.start();//真正地启动线程 + myThread2.start();//真正地启动线程 + + /* + 想让当前线程暂停10毫秒,再执行 + public static void sleep(long millis) :使当前正在执行的线程以指定的毫秒数暂停(暂时停止执行)。 + */ + //Thread.sleep(10); + /* + 主线程的名称到底叫什么???获取主线程对象,调用它的getName即可 + public static Thread currentThread() :获取到当前正在执行的线程对象。(重点) + */ + Thread mainThread = Thread.currentThread(); + System.out.println("主线程的名称:"+mainThread.getName()); + + System.out.println("程序结束"); + } +} diff --git a/s-day06/src/com/inmind/thread01/MyThread.java b/s-day06/src/com/inmind/thread01/MyThread.java new file mode 100644 index 0000000..710ba3e --- /dev/null +++ b/s-day06/src/com/inmind/thread01/MyThread.java @@ -0,0 +1,19 @@ +package com.inmind.thread01; + +//自定义的线程类 +public class MyThread extends Thread{ + public MyThread() { + } + + public MyThread(String name) { + super(name); + } + + @Override + public void run() { + for (int i = 0; i < 10; i++) { +// System.out.println(this.getName()+"---"+i); + System.out.println("子线程"+Thread.currentThread().getName()+"---"+i); + } + } +}