Proces和Thread
- 程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念,是一个静态的概念。
- 进程则是执行程序的一次执行过程,是一个动态的概念。
- 一个进程中可以包含若干个线程,线程是CPU调度和执行的单位。线程是独立的执行路径。
- 在一个进程中如果开辟了多个线程,线程的运行由调度器安排调度,调度器与操作系统紧密相关的,先后顺序不能人为的干预。
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制;线程会带来额外的开销,如CPU调度时间,并发控制开销。
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致。
只有主线程一条执行路径时,没问题;
多条执行路径,主线程和子线程并行交替执行。
Thread类
// 创建线程方法一:继承Thread()类,重写run()方法,调用start开启线程
public class TestThread1 extends Thread{
@Override
public void run() {
// run()方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("--------");
}
}
public static void main(String[] args) {
// main线程,主线程
// 创建线程对象
TestThread1 testThread1 = new TestThread1();
// 调用start()方法
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("--" + i);
}
}
}
总结:注意,线程开启不一定立即执行,由CPU调度执行
网图下载
package demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
// 练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;
private String name;
public TestThread2(String url, String name) {
this.url = url;
this.name = name;
}
// 下载图片线程的执行体
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载的文件名为:" + name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "1.png");
TestThread2 t2 = new TestThread2("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "2.png");
TestThread2 t3 = new TestThread2("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "3.png");
// 先下载t1
t1.start();
// 然后t2
t2.start();
// 最后t3
t3.start();
}
}
// 下载器
class WebDownloader {
// 下载方法
public void downloader(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
- 首先我们想要下载网上图片,需要一个下载器WebDownloader,里面有一个下载方法downloader,我们使用FileUitls里的一个工具类copyURLToFile,在这个工具类里面new一个url和name,并且做一个try/catch;
- 下载器方法写好了,我们还需要一个线程类,让TestThread继承Thread类,将下载方法里的url和name写为静态变量;
- 接着写一个构造器TestThread();
- 接着重写run()方法作为下载图片线程的执行体,里面通过构造器创建下载器webDownloader的实现类对象,下载成功输出一下下载了什么;
- main主函数里创建了三个线程实现类对象,通过start启动
Runnable接口类
// 创建线程方式2:实现Runnable接口,重写run()方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread3 implements Runnable{
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码" + i);
}
}
public static void main(String[] args) {
// 创建Runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
// 创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread(testThread3);
//
// thread.start();
// 匿名对象
new Thread(testThread3).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程--" + i);
}
}
}
上面网图下载也可转换为Runnable接口类
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
// 练习Thread,实现多线程同步下载图片
public class TestThread2_Runnable implements Runnable{
private String url;
private String name;
public TestThread2_Runnable(String url, String name) {
this.url = url;
this.name = name;
}
// 下载图片线程的执行体
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载的文件名为:" + name);
}
public static void main(String[] args) {
TestThread2_Runnable t1 = new TestThread2_Runnable("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "1.png");
TestThread2_Runnable t2 = new TestThread2_Runnable("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "2.png");
TestThread2_Runnable t3 = new TestThread2_Runnable("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "3.png");
// 先下载t1
new Thread(t1).start();
// 然后t2
new Thread(t2).start();
// 最后t3
new Thread(t3).start();
}
}
// 下载器
class WebDownloader {
// 下载方法
public void downloader(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
继承Thread类
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP但继承类局限性
实现Runnable接口
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象 + Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
龟兔赛跑
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("兔子") && i%10 == 0){
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();
}
}
- Race实现Runnable接口类
- 定义一个静态变量winner
- 重写run()方法,在100步内,打印此时线程跑了多少步
- 加入判断是否比赛结束,定义一个gameOver方法,如果winner不为空,直接返回true;如果≥100步,则得到此时线程运行者,并返回winner的名字和true,否则返回false;
- 接着定义一个boolean flag,如果gameOver返回的是true,那么直接退出循环,否则继续
- 在main主函数里构造race对象,创造两个线程,分别为乌龟和兔子
- 由于cpu执行太快了,再创建一个if判断,如果线程等于兔子或者每十步,让兔子等待10ms,并对此try/catch
实现Callable()接口
import java.util.concurrent.*;
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(String url, String name) {
this.url = url;
this.name = name;
}
// 下载图片线程的执行体
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载的文件名为:" + name);
return true;
}
public static void main(String[] args) throws Exception {
TestCallable t1 = new TestCallable("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "1.png");
TestCallable t2 = new TestCallable("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "2.png");
TestCallable t3 = new TestCallable("\thttps://i0.hdslb.com/bfs/sycp/creative_img/202204/12af13ed703a3218281914dad617cfb7.png@.webp", "3.png");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
// 获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
// 关闭服务
ser.shutdownNow();
}
}
线程创建方式三:实现Callable()接口
- Callable的好处
- 可以定义返回值
- 可以抛出异常
静态代理模式
// 静态代理模式总结:
// 真实对象和代理对象都要实现同一个接口
// 代理对象要代理真实角色
// 好处:
// 代理对象可以做很多真实对象做不了的事情
// 真实对象专注自己的事情
public class StaticProxy {
public static void main(String[] args) {
You you = new You(); // 你要结婚
// new Thread(new Runnable() {
// @Override
// public void run() {
//
// }
// }).start();
// Lamda表达式
new Thread(() -> System.out.println("我爱你!")).start();
new WeddingCompany(new You()).HappyMarry();
// WeddingCompany weddingCompany = new WeddingCompany(you);
// weddingCompany.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 before() {
System.out.println("结婚之前,布置现场");
}
private void after() {
System.out.println("结婚之后,收尾款");
}
}
静态代理模式总结:
真实对象和代理对象都要实现同一个接口
代理对象要代理真实角色
好处:
- 代理对象可以做很多真实对象做不了的事情
- 真实对象专注自己的事情
Lamda表达式
- 避免匿名内部类定义过多
package Lambda;
public class TestLambda2 {
public static void main(String[] args) {
ILove love = null;
// ILove love = new Love();
// love.love(2);
//
// class Love2 implements ILove {
// @Override
// public void love(int a) {
// System.out.println("i love you2-->" + a);
// }
// }
// love = new Love2();
// love.love(3);
//
// love = new ILove() {
// @Override
// public void love(int a) {
// System.out.println("i love you3-->" + a);
// }
// };
// love.love(4);
//
love = (a, b, c) -> {
System.out.println("i love you4-->" + a + b + c);
};
love.love(520, 502, 250);
// 总结:多个参数也可以去掉参数类型,要去掉都去掉
//
// // 简化:去掉括号
// love = a -> {
// System.out.println("i love you5-->" + a);
// };
// love.love(5);
// 简化2:去掉花括号
// love = a -> System.out.println("i love you5-->" + a);
// // 总结:可以去掉花括号的原因:必须只有一行代码,如果有多行,最多可以去掉括号,花括号去不掉!
// love.love(6);
}
}
interface ILove {
void love(int a, int b, int c);
}
//class Love implements ILove {
// @Override
// public void love(int a) {
// System.out.println("i love you1-->" + a);
// }
//}
线程休眠
import java.text.SimpleDateFormat;
import java.util.Date;
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();
}
}
// tenDown();
}
// 模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true) {
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
}
线程同步机制
-
队列和锁
-
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题∶
-
一个线程持有锁会导致其他所有需要此锁的线程挂起;
-
在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
-
如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题。
买票问题
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station, "苦逼的我").start();
new Thread(station, "牛逼的你们").start();
new Thread(station, "可恶的黄牛党").start();
}
}
class BuyTicket implements Runnable {
// 票
private int ticketNums = 10;
boolean flag = true; // 外部停止方式
@Override
public void run() {
// 买票
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
// 判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
Thread.sleep(100);
// 买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
银行取款问题
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50, "你");
Drawing gf = new Drawing(account, 100, "gf");
you.start();
gf.start();
}
}
class Account {
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
class Drawing extends Thread {
Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account, int drawingMoney, String name) {
super(name); // super必须在构造器最前面
this.account = account;
this.drawingMoney = drawingMoney;
}
// synchronized 默认锁的是this
@Override
public void run() {
// 锁的对象是变化的量。需要增删改的对象
synchronized (account) {
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够了,取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
}
不安全的集合问题
import java.util.ArrayList;
import java.util.List;
// 线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(() -> {
synchronized (list) {
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
java里
java.util.concurrent
包自带的线程安全的集合CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList;
// 测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(() -> {
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
死锁
- 多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有两个以上对象的锁时,就可能会发生“死锁”的问题。
// 死锁:多个线程互相拥抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup girl1 = new Makeup(0, "灰姑娘");
// girl1.start();
Makeup girl2 = new Makeup(1, "白雪公主");
// new Thread(new Makeup(1, "白雪公主"), "girl2").start();
girl1.start();
girl2.start();
}
}
// 口红
class Lipstick {
}
// 镜子
class Mirror {
}
// 化妆
class Makeup extends Thread {
// 需要的资源只有一份,用static保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice; // 选择
String girlName; // 使用化妆品的人
public Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 化妆的方法
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { // 获得口红的锁
System.out.println(this.girlName + "获得了口红的锁");
Thread.sleep(1000);
}
synchronized (mirror) { // 一秒钟后想获得镜子
System.out.println(this.girlName + "获得了镜子的锁");
}
} else {
synchronized (mirror) { // 获得镜子的锁
System.out.println(this.girlName + "获得了镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick) { // 二秒钟后想获得口红
System.out.println(this.girlName + "获得了口红的锁");
}
}
}
}
Lock锁
Lock代码块
class A {
private final ReentrantLock lock = new ReentrantLock();
public void m {
lock.lock();
try {
// 保证线程安全的代码;
} finally {
lock.unlock();
// 如果同步代码块有异常,要将unlock()写入finally语句块
}
}
}
买票的例子
import java.util.concurrent.locks.ReentrantLock;
// 测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2, "111").start();
new Thread(testLock2, "222").start();
new Thread(testLock2, "333").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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "获得了第" + ticketNums-- + "票");
} else {
break;
}
} finally {
// 解锁
lock.unlock();
}
}
}
}
生产者消费者问题,利用缓冲区解决:管程法
// 测试:生产者消费者模型-->利用缓冲区解决:管程法
// 生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
// 生产者
class Productor extends Thread {
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
// 生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Producer(i));
System.out.println("生产了" + i + "个产品");
}
}
}
// 消费者
class Consumer extends Thread {
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
// 消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了----->" + container.pop().id + "个产品");
}
}
}
// 产品
class Producer {
int id;
public Producer(int id) {
this.id = id;
}
}
// 缓冲区
class SynContainer {
// 需要一个容器大小
Producer[] producers = new Producer[10];
// 容器技术器
int count = 0;
// 生产者放入产品
public synchronized void push(Producer producer) {
// 如果容器满了,就需要等待消费者消费
while (count == producers.length) {
// 通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果容器没满,我们就需要放入产品
producers[count] = producer;
count++;
// 可以通知消费者消费了
this.notifyAll();
}
// 消费者消费产品
public synchronized Producer pop() {
// 判断是否消费
while (count == 0) {
// 等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果可以消费
count--;
Producer producer = producers[count];
// 吃完了,通知生产者生产
this.notifyAll();
return producer;
}
}
信号灯法
// 测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Actor(tv).start();
new Audience(tv).start();
}
}
// 生产者-->演员
class Actor extends Thread {
TV tv;
public Actor(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
this.tv.act("快乐大本营播放中");
} else {
this.tv.act("抖音:记录美好生活");
}
}
}
}
// 消费者-->观众
class Audience extends Thread {
TV tv;
public Audience(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
// 产品-->节目
class TV {
// 演员表演,观众等待
// 观众表演,演员等待
String voice; // 表演的节目
boolean flag = true;
// 表演
public synchronized void act(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;
}
}