Thread类的基本用法
一.线程的创建
Thread 是 JAVA 标准库中描述一个线程的类,
我们常用的创建线程的方法有下面几种~
1.定义类来继承Thread,重写run()方法
run方法就表示线程要执行的具体任务(代码)
class MyThread extends Thread{
//重写run()方法
@Override
public void run() {
while(true) {
System.out.println("hello");
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Thread t = new MyThread();
//start()方法就会在操作系统中真的创建出一个线程来,并运行run方法中的具体任务
t.start();
//直接调用run()也可以实现代码的运行,但是这种调用方式并没有创建线程
//t.run();
}
2.实现 Runnable接口, 重写 run()
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("hello");
}
}
public class ThreaDemo3 {
public static void main(String[] args) {
//本质上和继承Thread重写run效果一样
Thread t = new Thread(new MyRunnable());
t.start();
}
}
3.继承 Thread, 重写 run,使用匿名内部类
public class ThreadDemo4