线程创建三种方式
进程和线程
进程是执行程序的一次执行过程,是系统资源分配单位。
通常在一个进程中可以包含若干个线程,线程是CPU调度和执行的单位。
\(\color{red}{注意}\):
很多线程是模拟出来的,真正的多线程是指有多个CPU。即多核,如服务器,如果是模拟出来的多线程,即在一个CPU的情况下,在同一个时间点,cpu只能执行一个代码,因为切换很快,所以就有同时执行的错觉。
线程创建的三种方式:
- Thread class 继承Thread类(重点)
- Runnable接口 实现runnable接口(重点 推荐使用)
- Callable接口 实现Callable接口(了解)
方式一:
//重写run()方法,调用start开启线程
//线程开启不一定立即执行,由cpu调度,但是要先开启线程
public class Thread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("=》》》我在多线程");
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
thread1.start();
for (int i = 0; i < 2000; i++) {
System.out.println("我在写代码《《《=");
}
}
}
方式二:
public class Thread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("=>>>我在多线程");
}
}
public static void main(String[] args) {
Thread2 thread2 = new Thread2();
new Thread(thread2).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在写代码<<<=");
}
}
}
import java.util.concurrent.Callable;
public class Thread3 implements Callable {
@Override
public Object call() throws Exception {
return null;
}
}
浙公网安备 33010602011771号