java 打基础 - 基础不牢,地动山摇,穿线基础入门到进阶
文章目录
- 线程从入门到进阶
- 一. 进程和线程
- 1.1 线程相关概念
- 1.1.1 程序(program)
- 1.1.2 进程
- 1.1.3 什么是线程
- 1.1.4 其他相关概念
- 1.1.5 java代码查看电脑CPU
- 二. 线程基本使用
- 2.1 创建线程的两种方式
- 2.2 jconsole资源管理平台
- 2.3 为什么start可以调用到run方法?
- 2.4 线程应用案例-实现Runnable接口,手写Thread的代理模式,理解Runnable创建线程的过程。
- 2.5 线程使用应用案例-多线程执行
- 三. 多线程售票问题
- 3.1 多线程售票超卖异常问题
- 3.2 通知线程退出
- 3.3 线程中断
- 3.4 线程插队
- 四. 守护线程
- 五. 线程的生命周期
- 六. 线程的同步
- 6.1 线程同步机制
- 6.2 互斥锁
- 6.3 线程死锁
- 6.4 释放锁
线程从入门到进阶
一. 进程和线程
1.1 线程相关概念
1.1.1 程序(program)
是为完成特定任务、用某种语言编写的一组指令的集合简单的说:就是我们写的代码.
1.1.2 进程
进程是指运行中的程序,比如我们使用QQ,就启动了一个进程,操作系统就会为该进程分配内存空间。当我们使用迅雷,又启动了一个进程,操作系统将为迅雷分配新的内存空间。
进程是程序的一次执行过程,或是正在运行的一个程序。是动态过程: 有它自身的
产生、存在和消亡的过程.
1.1.3 什么是线程
1.线程由进程创建的,是进程的一个实体
2.一个进程可以拥有多个线程
1.1.4 其他相关概念
1.单线程:同一个时刻,只允许执行一个线程
2.多线程: 同一个时刻,可以执行多个线程,比如: 一个qq进程,可以同时打开多个聊天窗口,-个迅雷进程,可以同时下载多个文件
3.并发:同一个时刻,多个任务交替执行,造成一种“貌似同时”的错觉,简单的说,单核cpu实现的多任务就是并发。
4.并行: 同一个时刻,多个任务同时执行。多核cpu可以实现并行
1.1.5 java代码查看电脑CPU
public class Test {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
//获取当前电脑的CPU数量/核心数
int nums = runtime.availableProcessors();
System.out.println(nums);
}
}
二. 线程基本使用
2.1 创建线程的两种方式
在java中线程来使用有两种方法
1.继承Thread 类,重写 run方法
2.实现Runnable接口,重写 run方法
public class Thread01 {
public static void main(String[] args) throws InterruptedException {
//创建Cat对象,可以当做线程使用
Cat cat = new Cat();
//启动线程
cat.start();
//说明: 当main线程启动一个子线程 Thread-0,主线程不会阻塞,会继续执行
System.out.println("主线程继续执行" + Thread.currentThread().getName());
for (int i = 0; i < 10; 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;
//重写run方法,写上自己的业务逻辑
@Override
public void run() {
while (true) {
//该线程每隔1秒。在控制台输出 “喵喵,我是小猫咪”
System.out.println("喵喵,我是小猫咪" + (++times) + " 线程名:" + Thread.currentThread().getName());
//让该线程休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//当times 到80,退出while,这时线程也就退出。。
if (times == 80) {
break;
}
}
}
}
流程
2.2 jconsole资源管理平台
2.3 为什么start可以调用到run方法?
假设我们上面的代码这样子调用cat.run();
//run方法就是一个普通的方法,没有真正的启动一个线程,就会把run方法执行完毕,才向下执行。
分析源码
进入到start方
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
这里面有个核心方法
start0();
private native void start0();
//start0() 是本地方法,是JVM调用,底层是c/c++实现
//真正实现多线程的效果, 是starto(),而不是 runstart() 方法调用 start0() 方法后,该线程并不一定会立马执行,只是将线程变成了可运行状态。具体什么时候执行,取决于CPU,由 CPU统一调度。
2.4 线程应用案例-实现Runnable接口,手写Thread的代理模式,理解Runnable创建线程的过程。
说明
1.java是单继承的,在某些情况下一个类可能已经继承了某个父类,这时在用继承Th read类方法来创建线程显然不可能了。
2.java设计者们提供了另外一个方式创建线程,就是通过实现Runnable接口来创建线程,这里底层使用了代理模式。
public class Thread02 {
public static void main(String[] args) {
Dog dog = new Dog();
//dog.start(); 这里不能调用start
Thread thread = new Thread(dog);
//创建了Thread对象,把 dog对象(实现Runnable),放入Thread
thread.start();
Tiger tiger = new Tiger();
ThreadProxy threadProxy = new ThreadProxy(tiger);
threadProxy.start();
}
}
class Animal {
}
class Tiger extends Animal implements Runnable {
@Override
public void run() {
System.out.println("老虎嗷嗷叫...");
}
}
//你可以把Proxy类当做 ThreadProxy
//线程代理类 ,模拟了一个极简的Thread类
class ThreadProxy implements Runnable {
private Runnable target = null;
@Override
public void run() {
if (target != null) {
target.run();//动态绑定(运行类型)
}
}
public ThreadProxy(Runnable target) {
this.target = target;
}
public void start() {
start0();
}
private void start0() {
run();
}
}
//通过实现Runnable接口,开发线程
class Dog implements Runnable {
int count = 0;
@Override
public void run() {
while (true) {
System.out.println("小狗汪汪叫..hi " + (++count) + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (count == 10) {
break;
}
}
}
}
2.5 线程使用应用案例-多线程执行
/**
* 线程使用应用案例-多线程执行
*/
public class Thread03 {
public static void main(String[] args) {
T1 t1 = new T1();
T2 t2 = new T2();
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
thread1.start();//启动第一个线程
thread2.start();//启动第二个线程
}
}
class T1 implements Runnable {
int count = 0;
@Override
public void run() {
while (true) {
//每隔1秒输出 “hello,world”,输出10次
System.out.println("hello world" + (++count));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (count == 60) {
break;
}
}
}
}
class T2 implements Runnable {
int count = 0;
@Override
public void run() {
while (true) {
//每隔1秒输出 “h1”,输出5次
System.out.println("hi" + (++count));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (count == 5) {
break;
}
}
}
}
小结:
1.从java的设计来看,通过继承Thread或者实现Runnable接口来创建线程本质上没有区别,从idk帮助文档我们可以看到Thread类本身就
2.实现了Runnable接口 start0->startO0I实现Runnable接口方式更加适合多个线程共享一个资源的情况,并且避免了单继承的限制。
三. 多线程售票问题
3.1 多线程售票超卖异常问题
/**
* 使用多线程,模拟三个窗口同时售票
*/
public class SellTicket {
public static void main(String[] args) {
SellTicket01 sellTicket01 = new SellTicket01();
SellTicket01 sellTicket02 = new SellTicket01();
SellTicket01 sellTicket03 = new SellTicket01();
//这里我们会出现超卖。
sellTicket01.start();//启动售票线程
sellTicket02.start();//启动售票线程
sellTicket03.start();//启动售票线程
}
}
class SellTicket01 extends Thread {
//让多个线程共享 ticketNum
private static int ticketNum = 100;
@Override
public void run() {
while (true) {
if (ticketNum <= 0) {
System.out.println("售票结束...");
break;
}
//休眠50毫秒
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票 " +
" 剩余票数 " + (--ticketNum));
}
}
}
3.2 通知线程退出
基本说明
1.当线程完成任务后,会自动退出。
2.还可以通过使用变量来控制run方法退出的方式停止线程,即通知方式
public class ThreadExit {
public static void main(String[] args) throws InterruptedException {
T t = new T();
t.start();
//如果希望main线程去控制t1 线程的终止,必须可以修改 Loop
//让t1 退出run方法,从而终止 t1线程 -> 通知方式
//让主线程休眠 10 秒,再通知 t1线程退出
Thread.sleep(10000);
t.setLoop(false);
}
}
class T extends Thread {
int count = 0;
//设置一个控制变量
private boolean loop = true;
public void setLoop(boolean loop) {
this.loop = loop;
}
@Override
public void run() {
while (loop) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("运行中..." + (++count));
}
}
}
3.3 线程中断
线程常用方法
常用方法第一组
1.setName //设置线程名称,使之与参数 name 相同
2.getName //返回该线程的名称
3.start //使该线程开始执行; Java 虚拟机底层调用该线程的 start0 方法
4.run //调用线程对象 run 方法;
5.setPriority //更改线程的优先级
6.getPriority //获取线程的优先级
7.sleep//在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)
8.interrupt //中断线程
注意事项和细节
1.start 底层会创建新的线程,调用run,run 就是一个简单的方法调用,不会启动新线程
2.线程优先级范围
3.interrupt,中断线程,但并没有真正的结束线程。所以一般用于中断正在休眠线程
4.sleep:线程的静态方法,使当前线程休眠
public class ThreadMethod01 {
public static void main(String[] args) {
T1 t1 = new T1();
t1.setName("!23");
t1.setPriority(Thread.MIN_PRIORITY);
t1.start();
//主线程打印5 hi,然后我就中断 子线程的休眠
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
System.out.println("hi " + i);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
t1.interrupt();//当执行到这里,就会中断 t线程的休眠。
}
}
class T1 extends Thread {
@Override
public void run() {
while (true) {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "吃包子..." + i);
}
try {
System.out.println(Thread.currentThread().getName() + "休眠中...");
Thread.sleep(20000);
} catch (InterruptedException e) {
//当该线程执行到一个interrupt 方法时,就会catch 一个 异常,可以加入自己的业务代码
System.out.println(Thread.currentThread().getName() + "被中断了");
}
}
}
}
3.4 线程插队
常用方法第二组
1.yield:线程的礼让。让出cpu,让其他线程执行,但礼让的时间不确定,所以也不一定礼让成功。
2.join:线程的插队。插队的线程一旦插队成功,则肯定先执行完插入的线程所有的任务案例: 创建一个子线程,每隔1s 输出 hello,输出 20次,主线程每隔1秒,输出 hi,输出 20次.要求: 两个线程同时执行,当主线程输出 5次后,就让子线程运行完毕,主线程再继续。
public class ThreadMethod02 {
public static void main(String[] args) throws InterruptedException {
T2 t2 = new T2();
t2.start();
for (int i = 0; i <= 20; i++) {
Thread.sleep(1000);
System.out.println("main");
if (i == 5) {
System.out.println("=====");
//join 线程插队
// t2.join();//相当于让t2线程先执行完毕
Thread.yield
上一篇:
复习翻转必备--JAVA基础期知识读本--"基础不牢,地动山摇
下一篇:
基础不牢,地动山摇