进程
是执行程序的一次执行过程,是一个动态的执行过程,是系统资源分配的单位
线程
一个进程包含若干个线程,一个进程中至少有一个线程,否则无意义,线程是CPU调度和执行的单位
- 线程是独立的执行路径
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,GC线程
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调查,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制
- 线程会带来额为的开销,如cpu调度时间,并发控制开销.
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
继承thread类 简单实例
package com.jpd1.thread;
// 创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
// 总结 1.线程开启不一定立即执行,由cpu调度执行
public class TestThread1 extends Thread {
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在学习---"+ i);
}
}
// main线程 , 主线程
public static void main(String[] args) {
// 创建一个线程对象
TestThread1 testThread1 = new TestThread1();
// 调用一个start()方法,开启线程
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("学习多线程---"+ i);
}
}
}
实现Runnable接口
传入目标对象+Thread对象.start()
避免单继承局限性,方便同一个对象被多个线程使用
// 创建线程方式2 : 实现runnable接口,重写run方法,执行线程需要丢入runnable接口的实现类,调用start方法
public class TestThread2 implements Runnable {
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在学习---"+ i);
}
}
// main线程 , 主线程
public static void main(String[] args) {
// 创建runnbale接口的实现类对象
TestThread2 testThread2 = new TestThread2();
// 创建线程对象,通过线程对象来开启线程,代理
// Thread thread = new Thread(testThread2);
// thread.start(); 两行可简写为下一行
new Thread(testThread2).start();
for (int i = 0; i < 20; i++) {
System.out.println("学习多线程---"+ i);
}
}
}
初时并发问题
// 多个线程同时操作同一个对象, 火车票例子
// 发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱.
public class TestThread4 implements Runnable{
// 票数
private int ticketNums = 10;
@Override
public void run() {
while (true) {
if(ticketNums<=0){
break;
}
// 模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第几张"+ticketNums--);
}
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛党").start();
}
}
龟兔赛跑案例
package com.jpd1.thread;
import com.sun.deploy.net.proxy.ProxyUnavailableException;
// 模拟龟兔赛跑
public class Race implements Runnable {
// 胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// 模拟兔子休息
if(Thread.currentThread().getName().equals("兔子")){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 判断比赛是否结束
boolean flag = gameOver(i);
// 如果比赛结束了,就停止程序
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"--->跑了"+i+"步");
}
}
// 判断是否完成比赛
private boolean gameOver(int steps){
// 判断是否有胜利者
if(winner!=null){ // 已经存在胜利者了
return true;
}{
if(steps >= 100){
winner = Thread.currentThread().getName();
System.out.println("winner is"+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
实现Callable接口
实现Callable接口,需要返回值类型
重写call方法,需要抛出异常
静态代理
package com.jpd1.thread;
// 静态代理模式总结
// 真实对象和代理对象都要实现同一个接口
// 代理对象要代理真实角色
// 好处:
// 代理对象可以做很多真实对象做不到的事
// 真实对象专注做自己的事情
public class StacticProxy {
public static void main(String[] args) {
You you = new You(); // 你要结婚
new Thread(()-> System.out.println("我的妈,懵了")).start();
// WeddingCompany weddingCompany = new WeddingCompany(you);
// weddingCompany.HappyMarry()
// 可简写为以下
new WeddingCompany(new You()).HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
// 真实角色,你去结婚
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("这人结婚很开心");
}
}
// 代理角色,帮助你结婚
class WeddingCompany implements Marry{
// 代理-->真实目标角色
private Marry target;
public WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry(); // 这就是真实对象
after();
}
private void after() {
System.out.println("结婚之后,布置现场");
}
private void before() {
System.out.println("结婚之前,收尾款");
}
}
Lamda 表达式
- 避免匿名内部类定义过多
- 去掉没有意义的代码,只留下核心逻辑
- 函数式接口: 任何接口,如果只包含唯一一个抽象方法,呢么它就是一个函数式接口
/*
推导lambda表达式
*/
public class TestLambda1 {
//3.静态内部类
static class Like2 implements ILike {
@Override
public void lambda() {
System.out.println("i like lambda2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
like = new Like2();
like.lambda();
// 4.局部内部类
class Like3 implements ILike {
@Override
public void lambda() {
System.out.println("i like lambda3");
}
}
Like3 like3 = new Like3();
like3.lambda();
// 5.匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike(){
@Override
public void lambda() {
System.out.println("i like lombda4");
}
};
like.lambda();
// 6.使用Lambda简化
like = () -> {
System.out.println("i like lambda5");
};
like.lambda();
}
}
// 1.定义一个函数式接口
interface ILike{
void lambda ();
}
// 2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("i like lambda");
}
}
简化
public class TestLamdba2 {
public static void main(String[] args) {
// 匿名内部类
Ilove ilove = new Ilove() {
@Override
public void love(int a) {
System.out.println("开始表演");
}
};
// lamdba
Ilove love = (int a) -> {
System.out.println("i love you 2-->" + a);
};
// 简化1. 参数类型
love = (a) -> {
System.out.println("就这");
};
// 简化2. 简化括号
love = a -> {
System.out.println("就这2");
};
// 简化3. 去掉花括号
love = a-> System.out.println("这");
// 总结: lambda表达式只有在一行代码的情况下才能简化成一行,多行用代码块包裹
// 前提是接口为函数式接口,只包含一个方法
// 多个参数也可以去掉参数类型,要去掉都去掉
love.love(520);
}
interface Ilove {
void love(int a);
}
}
线程的五大状态
创建: Thread t = new Thread()
就绪: 调用Start()方法,线程立即进入就绪状态,不意味着立即调度执行
阻塞: 当调用sleep,wait或同步锁定时,线程进入阻塞状态,代码不再往下执行,阻塞事件解除后,重新进入就绪状态,等待cpu调度执行
运行: 进入运行状态,线程才真正执行线程体的代码块
死亡: 线程中断或者结束,一旦静=进入死亡状态,就不能再次启动
停止线程
package com.jpd1.thread;
// 1.建议线程正常停止--->利用次数,不建议死循环
// 2.建议使用标志位
// 3.不要使用stop或destory等过时或JDK不建议使用的方法
public class TestStop implements Runnable{
// 1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run...Thread"+i++);
}
}
// 2. 设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
if (i == 900){
// 调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
线程休眠 sleep(时间)指定当前线程阻塞的毫秒数,存在异常需要抛出,可以模拟网络延时,倒计时
每一个对象都有一个锁,sleep不会释放锁
// 模拟倒计时
public class TestSleep2 {
public static void main(String[] args) {
// 打印当前系统时间
Date startTime = new Date(System.currentTimeMillis());// 获取系统当前时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());// 更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
线程礼让
// 测试礼让线程
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield(); // 礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
强制执行
Join合并线程,此线程执行完成后,再执行其他线程,其他线程阻塞
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程VIP来了");
}
}
public static void main(String[] args) throws InterruptedException {
// 启动线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
// 主线程
for (int i = 0; i < 500; i++) {
if(i == 200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
观测线程状态
package com.jpd1.thread;
// 观察测试线程的状态
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("........");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state); // new
// 观察启动后
thread.start();// 启动线程
state = thread.getState();
System.out.println(state); // Run
while (state != Thread.State.TERMINATED){ // 只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState(); // 更新线程状态
System.out.println(state); // 输出状态
}
thread.start();
}
}
线程的优先级(priority)
package com.jpd1.thread;
// 测试线程的优先级
public class TestPriority {
public static void main(String[] args) {
// 主线程默认优先级
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
Thread thread4 = new Thread(myPriority);
Thread thread5 = new Thread(myPriority);
// 设置优先级
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY); // 10
thread4.start();
thread5.setPriority(-1);
thread5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护线程(daemon)
线程分为用户线程和守护线程
// 测试守护线程
// 上帝守护人类
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true); // 默认是false表示是用户线程,正常的线程都是用户线程
thread.start();// 上帝守护线程启动
new Thread(you).start(); // 你用户线程启动
}
}
// 上帝
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝保佑着我");
}
}
// 你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你开心的活着");
}
System.out.println("-===goodbye! world"); // Hello,world!
}
}
}
线程同步
多个线程操作同一个资源
并发: 同一个对象被多个线程同时操作
package com.jpd1.thread;
import java.util.ArrayList;
import java.util.List;
// 线程不安全的集合
public class UnsafeList {
public synchronized static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(200);
System.out.println(list.size());
}
}
死锁
lock锁
用Lock对象充当显示定义同步锁
package com.jpd1.thread;
import javax.swing.*;
import java.util.concurrent.locks.ReentrantLock;
// 测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
// 定义Lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true){
try{
lock.lock(); // 加锁
if(ticketNums>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
// 解锁
lock.unlock();
}
}
}
}
线程协作
信号灯法
package com.jpd1.thread;
// 测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
// 生产者-->演员
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2==0){
this.tv.play("辉白");
}else{
this.tv.play("白辉");
}
}
}
}
// 消费者-->观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
// 产品-->节目
class TV{
// 演员表演的时候,观众等待 T
// 观众观看,演员等待 F
String voice; // 表演的节目
boolean flag = true;
// 表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了"+voice);
// 通知观众观看
this.notifyAll();// 通知唤醒
this.voice = voice;
this.flag = !this.flag;
}
// 观看
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
// 通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
线程池
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,可以避免频繁创建销毁,实现复用
可提高响应速度,降低资源消耗,便于线程管理
package com.jpd1.thread;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 测试线程池
public class TestPool {
public static void main(String[] args) {
// 1.创建服务,创建线程池
// newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
// 2.关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
回顾
线程的三种启动方式
package com.jpd1.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.FutureTask;
// 回顾总结线程的创建
public class ThreadNew {
public static void main(String[] args) {
// 不同方法的启动方式
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
// 1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1");
}
}
// 2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
// 3.实现Callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}