public class test extends Thread{
@Override
public void run() {
System.out.println("我是一个线程");
}
public static void main(String[] args) {
test test1 = new test();
test1.start();
}
}
2.线程中断(使用interrupt)private static void test2() {
Thread thread = new Thread(() -> {
while (true) {
Thread.yield();
if (Thread.currentThread().isInterrupted()) {
System.out.println("线程被中断,程序退出。");
return;
}
}
});
thread.start();
thread.interrupt();
}
3.线程等待(sleep())
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Runnable target = () -> {
for (int i = 0; i < 10; i++) {
try {
System.out.println(Thread.currentThread().getName()
+ ": 我还在工作!");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": 我结束了!");
};
Thread thread1 = new Thread(target, "李四");
Thread thread2 = new Thread(target, "王五");
System.out.println("先让李四开始工作");
thread1.start();
thread1.join();
System.out.println("李四工作结束了,让王五开始工作");
thread2.start();
thread2.join();
System.out.println("王五工作结束了");
}
}
4.线程休眠(sleep)
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println(System.currentTimeMillis());
Thread.sleep(3 * 1000);
System.out.println(System.currentTimeMillis());
}
}
5.获取线程实例
public class test {
public static void main(String[] args) {
System.out.println( Thread.currentThread().getName());
}
}