多线程(一)线程类Thread基本应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011377803/article/details/72667278

java线程是一个高级话题,面试中经常会问到。本文分为两部分介绍,第一部分介绍java线程的生命周期,有一个概念上的认识。第二部分介绍Thread类的使用,和实际场景中的一些方法。(本文jdk 1.8)

一、生命周期

如果你想了解线程,就需要先了解线程状态,和Java线程生命周期。下面看图1,是基本的线程生命周期。


图1

如图1,我们可以清晰的看出线程的生命周期,用语言表述为线程状态: 新建->就绪->运行->阻塞->结束。

再来看一下Java的线程生命周期变化。如图2



图2

此图中可以清晰的看出Java线程的生命周期,线程生命周期主要有3个部分:创建、阻塞、运行。

阻塞是我们分析的重点,也是同步并发处理的基石:

阻塞分为3种:

1.等待阻塞::没有cpu时间片

2.锁阻塞:同步锁阻塞,进入锁池

3.其他阻塞:join 、sleep(不释放锁资源)、wait(释放锁资源)

二、Thread的使用

1.获取当前线程

	/**
	 * 获取当前线程
	 */
	public void currentThread(){
		Thread currentThread = Thread.currentThread();
		System.out.println(currentThread);
	}
这是最基础的方法,很多时候用这个线程来获取classLoad。

2.join

join会发生线程谦让,类似于插队某个线程插入线程优先级最高。
	/**
	 * join方法测试
	 * @throws InterruptedException
	 */
	public void join() throws InterruptedException{
		Thread thread = new Thread(()->{
			for(int i=0;i<10;i++){
				System.out.println("one ");
			}
		});
		Thread thread1 = new Thread(()->{
			try {
				//注意让thread进行插队
				thread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			for(int i=0;i<10;i++){
				System.out.println("two ");
			}
		});
		thread.start();
		thread1.start();
	}
以上用法,会先输入one,后输入two。不推荐这种写法,线程变为了串行操作,其实更多可以用于调整线程的执行顺序。

3. interrupt

线程中断,让一个线程终止,我们会想到stop,但是stop会发生死锁,是不安全的。所以我们采用中断的方法。
package com.ldh.threadtest;

public class Interrupt extends Thread{
	@Override
	public void run() {
		while(!Thread.currentThread().isInterrupted()){
			System.out.println("线程没有中断");
		}
		System.out.println("over");
	}
	
	public static void main(String[] args) throws InterruptedException {
		Interrupt interrupt = new Interrupt();
		interrupt.start();
		interrupt.interrupt();
	}
}

 以上代码会打印over。不过本文是显示Thread的方法。此方法不是最优解法。容易出现中断异常。 
 

public class Interrupt extends Thread{
	@Override
	public  void run() {
		while(true){
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		Interrupt interrupt = new Interrupt();
		interrupt.start();
		interrupt.interrupt();
	}
}

以上代码会出现了。

后面会继续讲解线程其他内容,并讲出其他中断解法。




猜你喜欢

转载自blog.csdn.net/u011377803/article/details/72667278
今日推荐