线程类
public class MyThread extends Thread{
public MyThread() {
}
public MyThread (String name){
super(name);
}
@Override
public void run() {
for (int i = 1; i < 6; i++) {
System.out.println(Thread.currentThread().getName()
+" thread is running~~~"+i);
}
}
}
执行类
涉及方法,getName,setName,Thread.currentThread()
public class ThreadApiDemo1 {
public static void main(String[] args) {
Thread th1 = new MyThread();
th1.start();
System.out.println(th1.getName());
Thread th2 = new MyThread();
th2.start();
System.out.println(th2.getName());
Thread th3 = new MyThread();
th3.setName("No.3");
th3.start();
Thread th4 = new MyThread("No.4");
th4.start();
Thread th = Thread.currentThread();
String thName = th.getName();
for (int i = 1; i < 6; i++) {
System.out.println(thName+" thread is running~~~"+i);
}
}
}
线程休眠方法
public class ThreadApiDemo2 {
public static void main(String[] args) throws InterruptedException {
Thread th = Thread.currentThread();
String thName = th.getName();
for (int i = 1; i < 6; i++) {
System.out.println(thName+" thread is running~~~"+i);
if (i == 3){
Thread.sleep(3000);
};
}
}
}
本文展示了如何在Java中创建线程并使用`Thread.currentThread()`获取当前线程,以及通过`Thread.sleep()`实现线程休眠。示例包括自定义线程类和线程休眠的用法,详细解释了线程执行流程。

被折叠的 条评论
为什么被折叠?



