一、线程
1、概念介绍
2、单线程和多线程
3、并发和并行
二、线程基本使用
1、创建线程的两种方式
(1)案例1:继承 Thread 类
注:在多线程编程里面,不是main方法结束了,就意味着进程就结束了
//演示通过继承 Thread 类创建线程
public class Thread01 {
public static void main(String[] args) throws InterruptedException {
//创建一个Cat 对象,可以当成线程使用
Cat cat = new Cat();
cat.start();//启动线程
// cat.run(); // run方法就是一个普通的方法,并没有真正的启动一个线程,
// 就会把run方法执行完毕,才会向下执行, 即会阻塞
//说明:当main线程启动一个子线程后,主线程不会阻塞,会继续执行
//这时,主线程和子线程是交替执行的
System.out.println("主线程继续执行"+"名字为:"+Thread.currentThread().getName());//名字为main
for (int i = 0; i < 60; i++) {
System.out.println("主线程 i+"+i);
//让主线程休眠
Thread.sleep(1000);
}
}
}
//说明
//1、当一个类继承了 Thread 类,该类就可以当做线程使用
//2、我们会重写 run 方法,写上自己的业务代码
//3、run Thread 类实现了 Runnable 接口的run方法
class Cat extends Thread{
int times = 0;
@Override
public void run() { //重写 run 方法,写上自己的逻辑
while (true) {
//每隔一秒,在控制台输出“喵喵,我是小猫咪”
System.out.println("喵喵,我是小猫咪"+(++times)+"线程名:"+Thread.currentThread().getName());
//让该线程休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(times == 80){
break;//当times 等于 80,退出 while循环,这时线程也就退出了
}
}
}
}
案例2:实现 Runnable 接口
//通过实现接口 Runnable 来开发线程
public class Thread02 {
public static void main(String[] args) {
Dog dog = new Dog();
//dog.start(); //这里不能调用start
//创建了Thread对