线程简介
线程,进程,多线程
线程实现(重点)
Thread、Runnable、Callable
线程创建的三种方式
-
Thread class -----> 继承Thread类(重点)
-
自定义线程类继承Thread类
-
重写run()方法,编写线程执行体
-
创建线程对象,调用start()方法启动线程
//创建线程方式一:继承Thread类,重写run()方法,调用start()开启线程 //总结:注意,线程开启后不一定立即执行 public class TestThread extends Thread{ @Override public void run() { //run方法线程体 for (int i = 0; i < 20; i++) { System.out.println("我在学习多线程--"+i); } } public static void main(String[] args) { //main方法,主线程 //创建一个线程对象 TestThread testThread = new TestThread(); //调用start()方法开启线程 testThread.start(); for (int i = 0; i < 200; i++) { System.out.println("我在敲代码--"+i); } } }
-
-
Runnable接口 -----> 实现Runnable接口(重点)
- 定义MyRunnable类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
//创建线程方式二:创建Runnable接口,重写run()方法,调用start()开启线程
//总结:注意,线程开启后不一定立即执行
public class TestThread implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程--"+i);
}
}
public static void main(String[] args) {
//创建一个线程对象
//调用start()方法开启线程
new Thread(TestThread).start();
//调用start()方法开启线程
// testThread.start();
//main方法,主线程
for (int i = 0; i < 200; i++) {
System.out.println("我在敲代码--"+i);
}
}
}
- Callable接口 -----> 实现Callable接口(了解)