关于线程你了解多少?
- 程序,进程,线程之间的关系
- 线程与进程的区别
- 线程的生命周期
- 多线程的创建方式
- 多线程安全问题(生产者消费者问题)
- 死锁问题
程序,进程,线程之间的关系
很多时候我们都会在书上看到这么一个概念:程序是一个指令的集合,进程是程序的一次静态执行过程,而线程是进程中一个单一的连续控制流程。通俗的理解:程序就是一个应用程序,好比微信这款应用程序,当我们运行微信程序的时候,需要登录自己的账号密码来运行,那么这就相当于一个进程,而微信这款程序在运行的过程中有聊天,朋友圈等功能,而这些功能就相当于线程。所以得出一个进程至少包含一个线程。
线程与进程的区别
区别 | 进程 | 线程 |
---|---|---|
根本区别 | 作为资源分配的单位 | 调度和执行的单位 |
开销 | 每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有较大的开销 | 同一类线程共享代码和数据空间,每个线程有独立的运行栈和程序计数器,线程切换的开销小 |
所处环境 | 在操作系统中能同时运行多个任务 | 在同一应用程序中有多个顺序流同时执行 |
分配内存 | 系统在运行的时候会成为每个进程分配不同的内存区域 | 除了CPU之外,不会为线程分配内存(线程获取的资源会在它所属的进程中进行争夺) |
包含关系 | 没有线程的进程是可以看作是单线程,如果一个进程内拥有多个线程,则执行过程不是串行的,而是多个线程共同完成 | 线程是进程的一部分,线程又称为轻量级进程 |
线程的生命周期
创建状态(新生态):也就是在创建Thread对象之后,还没调用start方法之前,属于线程的创建状态
就绪状态:准备开始执行,但是没有开始执行,表示调用start方法之后,当对应的线程创建完成,且调用start方法之后,所有的线程会处于一个就绪队列中, 所有线程都会去抢占CPU资源
运行状态:当当前进程抢占到CPU资源,就绪队列中的所有线程会去抢占CPU资源,谁先抢占到就先执行,这个执行的过程就称为运行状态,抢占到资源,代码先执行
终止状态:当运行的线程正常执行完所有代码逻辑,或者是因为异常而导致程序结束,进入的方式:正常运行,人为终端,调用stop方法,程序抛出异常未捕获
阻塞状态:在程序运行过程中,因发生某些异常而导致程序无法正常执行下去,此时会进入阻塞状态,进入阻塞状态的原因消除之后,所有阻塞队列会再次进入就绪队列,随机抢占cpu资源,等待执行,进入的方式:通过调用sleep方法,还有就是等待io资源
多线程的创建方式
- 继承Thread类
- 实现Runnable接口
- 实现Callable接口
- 使用 Executors 工具类创建线程池
通过继承Thread,注意需要使用start方法才可以
/**
* 启动线程的四种方式:
* 方法一:继承Thread
* 注意:继承Thread类之后需要调用start方法才能使用
*/
public class ThreadTest extends Thread{
@Override
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println("threadName:" + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.start();
for (int i = 0; i < 10; i++) {
System.out.println("threadName:" + Thread.currentThread().getName());
}
}
}
实现Runnable接口,然后再通过Thread类的start方法进行,注意其中包含了设计模式中的代理模式,需要创建Thread对象来进行调用,因为Runnable接口中没有start方法,要调用Thread中start方法进行实现
/**
* 启动线程的四种方式:
* 第二种:通过继承Runnable接口
* 注意:需要创建Thread对象来进行调用,代码的编写顺序也要注意,不然看不出效果
* 其中该方法使用了代理模式,为什么说使用了代理模式,应该创建了Thread对象,但是实际干活的还是Runnable接口的类
*
*/
public class ThreadTest2 implements Runnable{
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("ThreadName:" + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
ThreadTest2 threadTest2 = new ThreadTest2();
Thread thread = new Thread(threadTest2);
thread.start();
for (int i = 0; i < 10; i++) {
System.out.println("ThreadName:" + Thread.currentThread().getName());
}
}
}
通过实现Callable接口,此方法可以获得一个Funture类型的返回值
/**
* 启动线程的四种方式:
* 第三种:通过实现Callable接口
*
*
*/
public class ThreadTest3 implements Callable<Integer> {
public Integer call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println("ThreadName:" +Thread.currentThread().getName());
}
return 1;
}
public static void main(String[] args) {
FutureTask<Integer> futureTask = new FutureTask<Integer>(new ThreadTest3());
Thread thread = new Thread(futureTask);
thread.start();
for (int i = 0; i < 10; i++) {
System.out.println("ThreadName:" + Thread.currentThread().getName());
}
}
}
Executors提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口,实现的类型有FixedThreadPool,CachedThreadPool,SingleThreadExecutor,ScheduledThreadPool
/**
* 启动线程的四种方式:
* 第四种:使用 Executors 工具类创建线程池
*
*/
public class ThreadTest4 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
executorService.execute(new Task());
}
executorService.shutdown();
}
}
class Task implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName()+"running");
}
}
多线程安全问题(生产者消费者问题)
首先我们要了解的是为什么多线程就会出现线程安全问题,拿一个我们经常遇到的例子来解释,在我们618,双11的时候,很多时候我们都会抢购某些商品,但是商品的数量是有限的,存在着一种情况,库存为1的商品,当我手机点进去抢购的时候,而另一个人也同时抢购,这时我抢购完,后台还没来得急修改数据,第二个人点进去访问到的库存还是为1,那么他也可以抢购成功,实际上没有这么多库存,却卖多了产品,那么就是所谓的线程不安全问题。
解决办法:
方法一:使用同步代码块
下面使用的是抢凳子的案例,ABCD四个线程去抢夺一个公有资源——凳子,凳子只有3张,每有线程抢到凳子,就会打印出信息
/**
* 解决线程安全问题:
* 方法一、使用同步代码块:
* synchronized(共享资源,共享对象,需要的是Object的子类){具体执行的代码块}
*/
public class ThreadSafeTest implements Runnable{
private int shareDesk = 3;
public void run() {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this){
if(shareDesk > 0){
System.out.println(Thread.currentThread().getName()+"抢到了凳子,剩余凳子数为:"+--shareDesk);
}
}
}
}
public static void main(String[] args) {
ThreadSafeTest threadSafeTest = new ThreadSafeTest();
Thread t1 = new Thread(threadSafeTest,"A");
Thread t2 = new Thread(threadSafeTest,"B");
Thread t3 = new Thread(threadSafeTest,"C");
Thread t4 = new Thread(threadSafeTest,"D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
演示结果:
方法二:使用同步方法
同样的例子,使用同步方法进行解决
/**
* 解决线程安全问题:
* 方法二:使用同步方法解决问题:
* 将核心的代码块移到一个方法中,使用关键字synchronized来进行修饰,此时不需要指定共享对象
*/
public class ThreadSafeTest2 implements Runnable{
private int shareDesk = 3;
public void run() {
rob();
}
public synchronized void rob(){
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(shareDesk > 0){
System.out.println(Thread.currentThread().getName()+"抢到了凳子,剩余凳子数为:"+--shareDesk);
}
}
}
public static void main(String[] args) {
ThreadSafeTest threadSafeTest = new ThreadSafeTest();
Thread t1 = new Thread(threadSafeTest,"A");
Thread t2 = new Thread(threadSafeTest,"B");
Thread t3 = new Thread(threadSafeTest,"C");
Thread t4 = new Thread(threadSafeTest,"D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
演示结果:
线程安全之生产者消费者问题
我们经常会遇到这类问题,可能会出现的情况有:
1、生产者没有生产东西,消费者就开始消费了
2、生产出来的东西,属性没有对上
下面用一个例子来说明生产者消费者所出现的问题,定义一个食物的类,包含两个属性,一个属性为食物的名字,另外一个属性为食物的产地
上代码:
public class Food {
private String name;
private String address;
public Food() {
}
public Food(String name, String address) {
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "Food{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
接下来定义消费者和生产者,其中生产者会交替生产出两种不同的食物:
public class Consumer implements Runnable {
private Food food;
public Consumer() {
}
public Consumer(Food food) {
this.food = food;
}
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++) {
System.out.println("消费者消费了" + this.food.getName() + "-------" + this.food.getAddress());
}
}
}
public class Producer implements Runnable{
private Food food;
public Producer() {
}
public Producer(Food food) {
this.food = food;
}
public void run() {
for(int i = 0;i < 10;i++){
if(i % 2 == 0){
food.setName("烤鸭");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
food.setAddress("北京");
}else{
food.setName("火锅");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
food.setAddress("重庆");
}
System.out.println("生产者生产了" + this.food.getName() + "-------" + this.food.getAddress());
}
}
}
最后定义测试类进行测试:
public class Test {
public static void main(String[] args) {
Food food = new Food();
Producer producer = new Producer(food);
Consumer consumer = new Consumer(food);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
测试结果:
结论:我们可以看到生产者还没进行生产,消费者就开始消费,而且食物的属性也没有对应上,因此我们需要考虑到要使用线程同步
解决生产者消费者问题:
方法一:在食物类中加入一个属性用于判断是否有库存,并且在食物的类中实现生产和消费的方法,特别要注意需要加上关键字synchronized
上代码:
public class Food {
private String name;
private String address;
//用于判断该食物是否有库存,如果有库存则返回true,否则返回false,一开始没生产就是为false
private boolean isExist = false;
public Food() {
}
public Food(String name, String address) {
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "Food{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
//生产者生产食物
public synchronized void set(String name,String address){
//当生产者抢占到资源,判断当前对象是否有库存,如果有,则通知消费者先进行消费,生产者先进行等待,否则就直接执行
if(isExist){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setName(name);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setAddress(address);
isExist = true;
notify();
System.out.println("生产者生产了" + this.getName() + "-------" + this.getAddress());
}
//消费者消费食物
public synchronized void get(){
// 如果没有库存的话,消费者无法进行消费,消费者进入阻塞状态
if(!isExist){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者消费了" + this.getName() + "-------" + this.getAddress());
isExist = false;
notify();
}
}
在消费者和生产者类中,只需要调用该方法即可
public class Producer implements Runnable{
private Food food;
public Producer() {
}
public Producer(Food food) {
this.food = food;
}
public void run() {
for(int i = 0;i < 10;i++){
if(i % 2 == 0){
food.set("烤鸭","北京");
}else{
food.set("火锅","重庆");
}
}
}
}
public class Consumer implements Runnable {
private Food food;
public Consumer() {
}
public Consumer(Food food) {
this.food = food;
}
public void run() {
for (int i = 0; i < 10; i++) {
food.get();
}
}
}
最后测试类中,需要创建一个食物类的实例,并向生产者和消费者的构造方法中传参
public class Test {
public static void main(String[] args) {
Food food = new Food();
Producer producer = new Producer(food);
Consumer consumer = new Consumer(food);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(consumer);
t1.start();
t2.start();
}
}
测试结果:
方法二:使用阻塞队列进行实现
public class Food {
private String name;
private String address;
public Food() {
}
public Food(String name, String address) {
this.name = name;
this.address = address;
}
@Override
public String toString() {
return "Food{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class ConsumerQueue implements Runnable{
private BlockingQueue<Food> blockingQueue;
public ConsumerQueue() {
}
public ConsumerQueue(BlockingQueue blockingQueue) {
this.blockingQueue = blockingQueue;
}
public void run() {
for (int i = 0; i < 10; i++) {
try {
Food food = blockingQueue.take();
System.out.println("消费者消费:" + food.getName() + "------" + food.getAddress());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerQueue implements Runnable{
private BlockingQueue<Food> blockingQueue;
public ProducerQueue() {
}
public ProducerQueue(BlockingQueue blockingQueue) {
this.blockingQueue = blockingQueue;
}
public void run() {
for (int i = 0; i < 10; i++) {
Food food = null;
if(i%2==0){
food = new Food("烤鸭","北京");
}else{
food = new Food("火锅","重庆");
}
System.out.println("生产者生产:"+ food.getName() + "-----" + food.getAddress());
try {
blockingQueue.put(food);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
BlockingQueue<Food> blockingQueue = new ArrayBlockingQueue(5);
ProducerQueue producerQueue = new ProducerQueue(blockingQueue);
ConsumerQueue consumerQueue = new ConsumerQueue(blockingQueue);
new Thread(producerQueue).start();
new Thread(consumerQueue).start();
}
}
测试结果:
死锁问题
关于死锁,我觉得用以下案例来解释会比较容易通俗易懂
我把自己的私房钱藏在了一张存折里,一天我老婆发现了这张存折,但是她不知道密码,有存折也是拿不到钱的,而我知道了密码,但是没有存折也是拿不到钱的,我和我老婆好比两个线程各占有一份资源,但是又需要彼此的资源,此时谁都不愿意让步,我们谁也拿不到钱,就是发生所谓的死锁。
关于线程我还有这些需要告诉你
线程中sleep、yield、join方法的区别
yield:就是把当前线程返回到等待队列中
join:就是在当前线程中加入一个新的线程,等join进来的线程执行完了,再执行当前线程,保证线程运行完成
sleep:使当前线程睡眠一定的时间,再继续执行
关于wait(),notify()方法
在多线程中,可以实现唤醒和等待的过程,但是唤醒和等待的操作属于object这个类,所以唤醒和等待不是当前线程,而是我们设置的共享对象或者共享变量
关于线程的优先级
线程的默认优先级为5,可以通过setPriority()方法进行修改,最小值为1,最大值为10,优先级越高更大几率优先执行,并不是绝对的