🎁🎁🎁🎁🎁🎁Java可以用四种方式来创建线程,如下
1)继承Thread类创建线程
2)实现Runnable接口创建线程
3)使用Callable和Future创建线程
4)使用线程池例如用Executor框架
方法一一一一一
//创建线程方法1:继承thread类,重写run()方法,调用start开启线程
//线程开启不一定立即执行,由cpu调度执行
public class Test05thread1 extends Thread {
@Override
// run 方法线程体
public void run() {
super.run();
for (int i = 0; i < 5; i++) {
System.out.println("我在写作业====" + i);
}
}
// main 线程,主线程
public static void main(String[] args) {
// 创建一个线程对象
Test05thread1 test05thread1 = new Test05thread1();
// 调用start方法开启线程
test05thread1.run();
for (int i = 0; i < 5; i++) {
System.out.println("main线程" + i);
}
}
方法二二二二二 (推荐使用)
//创建一个线程类MyRunnable实现Runnable接口
//实现run()方法,调用start()方法开启线程======推荐使用
public class Test05thread2 implements Runnable{
//重写 run 方法线程体
@Override
public void run() {
for (int i = 0; i <5; i++) {
System.out.println("我正在学习==="+i);
}
}
public static void main(String[] args) {
// main 线程,主线程
Test05thread2 test05thread2=new Test05thread2();
//创建一个线程对象,通过线程对象开启线程
// Thread thread = new Thread(test05thread2);
// // 调用start方法开启线程
// thread.start();
new Thread(test05thread2).start();
for (int i = 0; i <5; i++) {
System.out.println("main方法"+i);
}
}