目录
6.1 JDK中用Thread.State枚举了线程的几种状态
1.线程相关概念
1.1 程序(program)
什么是程序:
是为了完成特定任务,用某种语言编写的一组指令的集合。简而言之,就是我们写的代码
1.2 进程
- 进程是指运行中的程序,每启动一个进程,操作系统就会为该进程分配内存空间。
- 进程是程序的一次执行过程,或是正在运行的一个程序,是动态过程:他有自身的产生、存在和消亡的过程。
1.3 什么是线程
- 线程由进程创建,是进程的一个实体。
- 一个进程可以拥有多个线程。
1.4 单线程和多线程
- 单线程:同一个时刻,只允许执行一个线程。
- 多线程:同一个时刻,可以执行多个线程。ps:一个QQ进程,可以同时打开多个聊天窗口;一个迅雷进程,可以同时下载多个文件。
1.5 并发和并行
- 并发:同一个时刻,多个任务交替执行,造成一种“貌似同时”的错觉。ps:单核cpu实现的多任务就是并发。
- 并行:同一个时刻,多个任务同时执行。 多核cpu可以实现并行
2. 线程的基本使用
2.1 创建线程的两种方式
- 继承Thread类,重写run方法。
- 实现Runnable接口,重写run方法。
2.1.1 继承Thread类创建线程
package thread;
//通过类继承Thread类实现创建线程
public class Thread01 {
public static void main(String[] args) throws InterruptedException {
//创建Cat,可以当做线程使用
Cat cat = new Cat();
//启动线程,最终会执行Cat的run()方法
cat.start();
//当main线程启动一个子线程Thread-0,主线程不会阻塞,会继续执行
//这时,主线程和子线程是交替执行..
System.out.println("主线程继续执行" + Thread.currentThread().getName());
//Thread.currentThread().getName()指当前线程的名字
for (int i = 0; i < 50; i++) {
System.out.println("主线程i= " + i);
//主线程休眠
Thread.sleep(300);
}
}
}
//1. Cat继承了 Thread 类, 该类就可以当做线程使用
//2. 重写 run 方法,写自己的业务代码
//3. run Thread 类 实现了 Runnable 接口的 run 方法
class Cat extends Thread {
int times = 0;
@Override
//run方法是一个普通的方法,没有真正的启动一个线程,run方法执行完毕,才向下执行
public void run() {
while(true){
//该线程每隔0.3秒,输出
System.out.println("喵喵喵~~~" + (++times) + Thread.currentThread().getName() );
//线程休眠0.3秒 1秒=1000毫秒
try {
Thread.sleep(300);//ctrl+alt+t快速处理异常
} catch (InterruptedException e) {
e.printStackTrace();
}
if(times == 50){
break;//当times到达50,退出while,线程也就退出
}
}
}
}
2.1.2 实现Runable接口创建线程
- java是单继承的,在某些情况下一个类可能已经继承了某个父类,这是再用继承Thread类方法来创建线程显然不可能了。
- 通过实现Runnable接口来创建线程,可以避免1.的情况。
package thread;
//通过实现Runable接口,实现创建线程
public class Thread02 {
public static void main(String[] args) {
Dog dog = new Dog();
//创建了 Thread 对象,把 dog 对象(实现了 Runnable接口),放入 Thread
Thread thread1 = new Thread(dog);
Thread thread2 = new Thread(dog);
//这里不能用dog调用start()方法,
thread1.start();
thread2.start();
}
}
class Dog implements Runnable{
int count = 0;
public void run(){
while(true){
System.out.println("小狗汪汪叫~~~" + ++count + Thread.currentThread().getName()) ;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(count == 50)
break;
}
}
}
2.1.3 多线程执行
package thread;
public class Thread03 {
public static void main(String[] args) {
T1 t1 = new T1();
T2 t2 = new T2();
Thread thread2 = new Thread(t2);
t1.start();
thread2.start();
}
}
class T1 extends Thread{
int counts = 0;
@Override
public void run() {
while(true){
System.out.println("hello,world!" + ++counts);
try {
Thread.sleep( 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(counts == 10)
break;
}
}
}
class T2 implements Runnable{
int counts = 0;
@Override
public void run() {
while(true){
System.out.println("hi!" + ++counts);
try {
Thread.sleep( 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(counts == 5)
break;
}
}
}