【Java并发】基础,Java并发
【Java并发】基础,Java并发
-
一、概述
- 1.1 线程与进程区别
- 1.2 多线程引发的性能问题
-
二、多线程创建方式
- 2.1 第一种-继承Thread类
- 2.2 第二种-实现Runnable接口
- 2.3 第三种-实现Callable接口
- 2.4 常用线程构造函数
- 2.5 使用继承Thread类还是使用实现Runnable接口好?
-
三、线程基础知识
- 3.1 常用线程API概述
- 3.2 守护线程
- 3.3 yield方法
- 3.4 join()方法作用
- 3.5 优先级
-
四、停止线程
- 4.1 interrupt方法介绍
- 4.2 判断线程是否是停止状态
- 4.3 利用异常的方式停止线程
-
五、多线程运行状态
- 5.1 线程状态概览
- 5.2 新建状态(NEW)
- 5.3 可运行状态(Runnbale)
- 5.4 阻塞状态(Blocked)
- 5.5 无限期等待(Waiting)
- 5.6 限期等待(Timed Waiting)
- 5.7 死亡(Terminated)
一、概述
1.1 线程与进程区别
- 进程就是程序的一次执行过程,是系统运行程序的基本单位,进程是动态的。系统运行一个程序就是一个进程从创建、运行到消亡的过程
- 在Java中,当我们启动main函数的时候就是启动了一个JVM进程,而main函数所在的线程就是这个进程中的一个线程。
- 每个正在系统上运行的程序都是一个进程。每个进程包含一到多个线程。线程是一组指令的集合,或者是程序的特殊段,它可以在程序里独立执行。也可以把它理解为代码运行的上下文。所以线程基本上是轻量级的进程,它负责在单个程序里执行多任务。通常由操作系统负责多个线程的调度和执行。
- 使用线程可以把占据时间长的程序中的任务放到后台去处理,程序的运行速度可能加快,在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下可以释放一些珍贵的资源如内存占用等等。
- 如果有大量的线程,会影响性能,因为操作系统需要在它们之间切换,更多的线程需要更多的内存空间,线程的中止需要考虑其对程序运行的影响。通常块模型数据是在多个线程间共享的,需要防止线程死锁情况的发生。
- 总结:进程是所有线程的集合,每一个线程是进程中的一条执行路径。
1.2 多线程引发的性能问题
- 消耗时间,线程的创建和销毁都需要时间,如果有大量的线程进行创建和销毁,那么这些时间的消耗会比较明显,导致性能上的缺失
- 非常的消耗CPU和内存:大量的线程创建、执行和销毁是非常的消耗cpu和内存的,这将直接影响系统的吞吐量,导致性能急剧下降,如果内存资源占用的比较多,还很可能造成OOM
- 容易导致GC频繁的执行:大量的线程的创建和销毁很容易导致GC频繁的执行,从而发生内存抖动现象,而发生了内存抖动,对于移动端来说,最大的影响就是造成界面卡顿
- 而针对上述所描述的问题,解决的办法归根到底就是:重用已有的线程,从而减少线程的创建。所以这就涉及到线程池(ExecutorService)的概念了,线程池的基本作用就是进行线程的复用。关于线程池的知识,以后再整理
二、多线程创建方式
2.1 第一种-继承Thread类
代码如下:
//1. 继承thread类,重写run方法,run方法中,需要线程执行代码
class ThreadDemo01 extends Thread {
// run方法中,需要线程需要执行代码
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.print("子线程id:" + this.getId() + ",");
System.out.print("子线程name:" + getName()+",");
System.out.println("子线程--->i:" + i);
}
}
}
// 1.什么是线程 线程是一条执行路径,每个线程都互不影响。
// 2.什么是多线程,多线程在一个进程中,有多条不同的执行路径,并行执行。目的为了提高程序效率。
// 3.在一个进程中,一定会主线程。
// 4.如果连线程主线程都没有,怎么执行程序。
// 线程几种分类 1. 用户线程、守护线程
// 2. 主线程 子线程 GC线程
public class T001_CreateWithThread {
// 交替执行
public static void main(String[] args) {
System.out.println("main... 主线程开始...");
// 1.创建线程
ThreadDemo01 threadDemo01 = new ThreadDemo01();
// 2.启动线程
threadDemo01.start();
for (int i = 0; i < 10; i++) {
System.out.println("main---> i: " + i);
}
System.out.println("main... 主线程结束...");
}
}
执行结果:
代码如下: 匿名内部类的方式 示例 运行结果 示例代码 执行结果 代码示例 执行结果 调用interrupt()方法后线程并没有马上停止,仅仅是在当前线程中打了一个停止的标记,并不是真正的停止线程。 源码如下 一个未捕获的异常终止了run方法而使线程猝死。 为了确定线程在当前是否存活着(就是要么是可运行的,要么是被阻塞了),需要使用isAlive方法。如果是可运行或被阻塞,这个方法返回true; 如果线程仍旧是new状态且不是可运行的, 或者线程死亡了,则返回false.System.out.println("-----多线程创建开始-----");
new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("线程 -- " + Thread.currentThread().getName() + "-->" + i);
}
};
}.start();
System.out.println("-----多线程创建结束-----");
2.2 第二种-实现Runnable接口
class ThreadDemo02 implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(" 子 i:" + i);
}
}
}
// 1.实现runable接口,重写run方法
public class T002_CreateWithRunnable {
public static void main(String[] args) {
System.out.println("main... 主线程开始...");
// 创建线程
ThreadDemo02 threadDemo02 = new ThreadDemo02();
/*
* 这里 用了Thread的另一个构造方法,
* 该构造方法可以传入一个Runnable的实现类
* 而我们查看Thread的源码可以得知,Thread类 原本就实现了Runnable
* 所里也可以传入一个Thread的对象,这样就可以把一个Thread对象中的run()
* 方法交由其他的线程进行调用
*/
Thread t1= new Thread(threadDemo02);
// 启动线程
t1.start();
for (int i = 0; i <10; i++) {
System.out.println("main..i:"+i);
}
System.out.println("main... 主线程结束...");
}
}
System.out.println("-----多线程创建开始-----");
Thread thread = new Thread(new Runnable() {
public void run() {
for (int i = 0; i< 10; i++) {
System.out.println("i:" + i);
}
}
}).start();
System.out.println("-----多线程创建结束-----");
2.3 第三种-实现Callable接口
/**
*
* Callbale接口 可以又返回值,可以抛出异常,
* 而Runnable接口 中的run方法没有返回值,异常只能捕获
*
* @author hao
*
*/
public class T002_CreateWithCallable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyCallable mc = new MyCallable();
FutureTask<Integer> ft = new FutureTask<Integer>(mc);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
}
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
return 124;
}
}
2.4 常用线程构造函数
2.5 使用继承Thread类还是使用实现Runnable接口好?
三、线程基础知识
3.1 常用线程API概述
3.2 守护线程
/*
* 什么是守护线程? 守护线程 进程线程(主线程挂了) 守护线程也会被自动销毁.
* 该示例中我们手动将子线程设置为守护线程,
* 当其他线程(该例中只有主线程)停止时守护线程也会终止
*/
public class DaemonThread {
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("我是子线程...");
}
}
});
thread.setDaemon(true);
thread.start();
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (Exception e) {
}
System.out.println("我是主线程");
}
System.out.println("主线程执行完毕!");
}
}
3.3 yield方法
/**
* yield方法的作用是放弃当前的CPU资源,
* 将它让给其他的任务去占用CPU执行时间,
* 但是放弃的时间不确定,有可能刚刚放弃,马上又获得CPU时间片
* @author hao
*
*/
public class T009_Yield {
public static void main(String[] args) {
YeildTestThread t1 = new YeildTestThread();
t1.start();
}
}
class YeildTestThread extends Thread{
@Override
public void run() {
super.run();
long beginTime = System.currentTimeMillis();
int count =0;
for(int i =0;i<5000000;i++) {
//Thread.yield();
count = count +(i+1);
}
long endTime = System.currentTimeMillis();
System.out.println("用时:"+(endTime-beginTime)+"毫秒!");
}
}
注释掉 Thread.yield(); 和没注释掉是的执行时间不同。3.4 join()方法作用
//创建一个线程,子线程执行完毕后,主线程才能执行。
public class T010_Join {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("子线程,i:" + i);
}
}
});
t1.start();
// 当前线程释放资格权,等t1执行完毕之后,才会继续进行执行。
t1.join();
for (int i = 0; i < 5; i++) {
System.out.println("main线程,i:" + i);
}
}
}
public class JoinThreadDemo02 {
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("t1,i:" + i);
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
t1.join();
} catch (Exception e) {
}
for (int i = 0; i < 20; i++) {
System.out.println("t2,i:" + i);
}
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
try {
t2.join();
} catch (Exception e) {
}
for (int i = 0; i < 20; i++) {
System.out.println("t3,i:" + i);
}
}
});
t1.start();
t2.start();
t3.start();
}
}
3.5 优先级
public class T011_Priority {
public static void main(String[] args) {
PrioritytThread prioritytThread = new PrioritytThread();
Thread t1 = new Thread(prioritytThread);
Thread t2 = new Thread(prioritytThread);
t1.start();
// 注意设置了优先级, 不代表每次都一定会被执行。 只是CPU调度会有限分配
t1.setPriority(10);
t2.start();
}
}
class PrioritytThread implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().toString() + "---i:" + i);
}
}
}
四、停止线程
4.1 interrupt方法介绍
4.2 判断线程是否是停止状态
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
public boolean isInterrupted() {
return isInterrupted(false);
}
/**
* Tests if some Thread has been interrupted.
* The interrupted state is reset or not
* based on the value of ClearInterrupted that is passed.
*
* 判断某些线程是否已经中断。
* 根据传入的ClearInterrupted值来决定是否要重置中断的状态
*/
private native boolean isInterrupted(boolean ClearInterrupted);
4.3 利用异常的方式停止线程
/**
* 利用抛出异常的方式来终止线程
* @author hao
*
*/
public class Test_ExceptionInterrupt {
public static void main(String[] args) {
try {
ExcepThread t = new ExcepThread();
t.start();
Thread.sleep(2000);
t.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}
class ExcepThread extends Thread{
@Override
public void run() {
this.stop();
try {
for(int i=0;i<500000;i++) {
if(Thread.interrupted()) {
System.out.println("已经是停止状态了,我要退出了!");
// break;
throw new InterruptedException();
}
System.out.println("i "+(i+1));
}
System.out.println("我被输出了 。线程并未停止! 只是for循环被中断了");
} catch (InterruptedException e) {
System.out.println("catch t ");
e.printStackTrace();
}
}
}
五、多线程运行状态
5.1 线程状态概览
5.2 新建状态(NEW)
5.3 可运行状态(Runnbale)
5.4 阻塞状态(Blocked)
5.5 无限期等待(Waiting)
5.6 限期等待(Timed Waiting)
5.7 死亡(Terminated)
相关文章
暂无相关文章
用户点评