1、直接继承Thread这个类,然后重写run方法
/**
* @author jeffchan 2020/04/14
*/
public class MyFirstThread extends Thread {
@Override
public void run() {
for (int i =0; i < 100;i++){
System.out.println("MyFirstThread "+ i);
}
}
}
在客户端的使用:
public class Main {
public static void main(String[] args) throws Exception{
Thread t = new Thread(new MyFirstThread());
t.start();
for (int i =0; i< 10000;i++){
System.out.println("main "+ i);
}
}
}
在控制台可以看到交替的打印,执行多次,发现结果也不一样
2、实现Runable接口的方式
/**
* @author jeffchan 2020/04/14
*/
public class MySecondThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++){
System.out.println("MySecondThread "+ i);
}
}
}
在客户端使用:
public class Main {
public static void main(String[] args) throws Exception{
Thread t = new Thread(new MyFirstThread());
t.start();
// 直接创建调用
new Thread(new MySecondThread()).start();
for (int i =0; i< 10000;i++){
System.out.println("main "+ i);
}
}
}
推荐使用实现runnable的方式,可以避免继承Thread的单继承的局限性。
线程的生命周期:
新建 (就是new的操作) 可运行(调用start()方法) 正在运行(调用了start()的方法,同时获得了cpu的使用权) 阻塞(调用了sleep方法,wait方法,或者等待io等) 终止(正常运行完,或者遇到异常退出)