【狂神说Java】多线程详解
进程是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。
进程相当于我们每次执行代码时的程序。
线程是操作系统能够进行运算调度的最小单位。一个进程可以包含多个线程。
多任务处理是指用户可以在同一时间内运行多个应用程序,每个应用程序被称作一个任务。Linux、windows就是支持多任务的操作系统,比起单任务系统它的功能增强了许多。
现实中大多数同时做多件事的例子,看起来是多个任务都在做,其实本质上我们的大脑在同一时间依旧只做了一件事
多线程(multithreading),是指从软件或者硬件上实现多个线程并发执行的技术。
很多多线程是模拟出来的,真正的多线程是指有多个CPU,即多核,如服务器。如果是模拟出来的多线程,即在一个CPU的情况下,在同一个时间点,CPU只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。
package com.Thread;
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("MyThread.run");
}
}
public static void main(String[] args) {
//new MyThread().run();而直接调用run方法是同步执行的
new MyThread().start();//可以看到结果是交替输出的
for (int i = 0; i < 1000; i++) {
System.out.println("i = " + i);
}
}
}
下载第三方包common-io,也可以下载下来本地导入,点jar跳转下载,也可以用maven。
package com.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class PracticeThread extends Thread{
public String url;
public String name;
public PracticeThread(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downLoad(url, name);
System.out.println("Success to download --> " + name);
}
public static void main(String[] args) {
PracticeThread practiceThread = new PracticeThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-04-03%2F5e86a06468c04.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=5f39ec0b09e7ac9f6439a877871894c5","1.jpg");
PracticeThread practiceThread1 = new PracticeThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdesk.fd.zol-img.com.cn%2Fg5%2FM00%2F07%2F01%2FChMkJlbNRtyIQK_HAAKWesRqbw8AALbQQF4I00AApaS166.jpg&refer=http%3A%2F%2Fdesk.fd.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=450f1e564dd0742d7196c1b3b1865f32","2.jpg");
PracticeThread practiceThread2 = new PracticeThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1114%2F0H120155P2%2F200H1155P2-8-1200.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=cd25aed25cf627a1caf78c1828ddbcec","3.jpg");
practiceThread.start();
practiceThread1.start();
practiceThread2.start();
}
}
class WebDownLoader{
public void downLoad(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
}
}
}
完成的顺序依照具体逻辑所需时间
实现接口与继承差不多,都需要重写run方法。但是更推荐使用接口类,因为这样能避免单继承的局限性,方便同一个对象被多个线程使用。
看下面的例子可以发现,开启线程是通过将类作为参数启动的,那么是不是可以多个线程都用同一个对象呢?当然是可以的
package com.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class PracticeThread implements Runnable{
public String url;
public String name;
public PracticeThread(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downLoad(url, name);
System.out.println("Success to download --> " + name);
}
public static void main(String[] args) {
PracticeThread practiceThread = new PracticeThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-04-03%2F5e86a06468c04.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=5f39ec0b09e7ac9f6439a877871894c5","1.jpg");
PracticeThread practiceThread1 = new PracticeThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdesk.fd.zol-img.com.cn%2Fg5%2FM00%2F07%2F01%2FChMkJlbNRtyIQK_HAAKWesRqbw8AALbQQF4I00AApaS166.jpg&refer=http%3A%2F%2Fdesk.fd.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=450f1e564dd0742d7196c1b3b1865f32","2.jpg");
PracticeThread practiceThread2 = new PracticeThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1114%2F0H120155P2%2F200H1155P2-8-1200.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=cd25aed25cf627a1caf78c1828ddbcec","3.jpg");
new Thread(practiceThread).start();
new Thread(practiceThread1).start();
new Thread(practiceThread2).start();
}
}
class WebDownLoader{
public void downLoad(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
}
}
}
抢票问题就是一个很明显的并发问题,我们来简单模拟一下抢票
Thread.currentThread().getName()
获取当前执行线程的名称Thread.sleep(200)
线程等待时间,单位是毫秒package com.Thread;
public class ConcurrentTest implements Runnable{
private int ticketNumbers = 10;
@Override
public void run() {
while (ticketNumbers > 0) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNumbers-- + "张票");
}
}
public static void main(String[] args) {
ConcurrentTest ticket = new ConcurrentTest();
new Thread(ticket, "小明").start();
new Thread(ticket, "小王").start();
new Thread(ticket, "小红").start();
}
}
细心的小伙伴就会发现如果只是并发地执行是会抢占资源的,也就是抢到同一张票,至于出现0和负数不用管它,那是因为sleep的原因导致的
首先规定了赛道距离,是线程的共同目标。接着判断谁先到达终点
如今计算机的处理速度非常快,单靠循环是辨别不出来谁快谁慢。况且谁先new谁就先被CPU调度,而循环的时间是非常快的。正常的CPU处理C++代码,1s可以执行 1 0 8 10^8 108次(如果没记错的话),也就是说你写的算法限制在1s中的话,你的复杂度是不能超过这个数量级的,常数大的话也可能过不了。
可以采用适当的时候使线程进入等待状态,这样两个线程的执行先后顺序会得到调整。
package com.Thread;
public class Example implements Runnable{
private static String winner;
@Override
public void run() {
boolean flag;
for (int i = 0; i <= 1000; i++) {
if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "---> 跑了" + i + "步");
flag = gameOver(i);
if (flag) {
break;
}
}
}
private boolean gameOver(int steps) {
if (winner != null) {
return true;
}
if (steps == 1000) {
winner = Thread.currentThread().getName();
System.out.println("winner is " + winner);
return true;
}
return false;
}
public static void main(String[] args) {
Example example = new Example();
new Thread(example, "兔子").start();
new Thread(example, "乌龟").start();
}
}
package com.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
public class MyCallable implements Callable<Boolean> {
public String url;
public String name;
public MyCallable(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownLoader1 webDownLoader = new WebDownLoader1();
webDownLoader.downLoad(url, name);
System.out.println("Success to download --> " + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable Thread = new MyCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-04-03%2F5e86a06468c04.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=5f39ec0b09e7ac9f6439a877871894c5","1.jpg");
MyCallable Thread1 = new MyCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdesk.fd.zol-img.com.cn%2Fg5%2FM00%2F07%2F01%2FChMkJlbNRtyIQK_HAAKWesRqbw8AALbQQF4I00AApaS166.jpg&refer=http%3A%2F%2Fdesk.fd.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=450f1e564dd0742d7196c1b3b1865f32","2.jpg");
MyCallable Thread2 = new MyCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1114%2F0H120155P2%2F200H1155P2-8-1200.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1629433325&t=cd25aed25cf627a1caf78c1828ddbcec","3.jpg");
//创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r = service.submit(Thread);
Future<Boolean> r1 = service.submit(Thread1);
Future<Boolean> r2 = service.submit(Thread2);
//获取结果
boolean rs = r.get();
boolean rs1 = r1.get();
boolean rs2 = r2.get();
System.out.println(rs);
System.out.println(rs1);
System.out.println(rs2);
//关闭服务
service.shutdown();
}
}
class WebDownLoader1{
public void downLoad(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
}
}
}
菜鸟教程 | 代理模式
在代理模式(Proxy Pattern)中,一个类代表另一个类的功能。这种类型的设计模式属于结构型模式。
Thread与实现了Runnable接口的类就是这种关系,它们都实现了同一接口(Runnable)。
Example:
package com.Thread;
// 静态代理模式总结:
// 真实对象和代理对象都要实现同一个接口
// 代理对象要代理真实角色
// 好处:
// 代理对象可以做很多真实对象做不了的事情
// 真实对象专注做自已的事情
public class StaticProxy {
public static void main(String[] args) {
WeddingCompany weddingCompany = new WeddingCompany(new You());
weddingCompany.HappyMarry();
// 对比这个静态代理模式,和多线程的格式,可以看到多线程其实也是一样的
// Thread实现了Runnable接口,而代理的对象同样也实现了Runnable接口
new WeddingCompany(new You()).HappyMarry();
new Thread(()-> System.out.println("我爱你")).start();// new Thread(() -> System.out.println("我爱你!")).start();
}
}
//结婚接口
interface Marry{
void HappyMarry();
}
//真实角色,你去结婚
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("结婚,Happy");
}
}
// 代理角色,婚庆公司,帮助你结婚
class WeddingCompany implements Marry{
private final 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("结婚之后,收拾残局");
}
}
(params) -> expression [表达式]
(params) -> statement [语句]
(params) -> { statements }
new Thread(() -> System.out.println("多线程学习")).start();
lambda 表达式只能引用标记了 final 的外层局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。如以下代码,编译会出错:
String first = "";
Comparator<String> comparator = (first, second) -> Integer.compare(first.length(), second.length());
理解Functional Interface (函数式接口)是学习Java8 Lambda表达式的关键所在
函数式接口的定义:
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口
public interface Runnable {
public abstract void run();
}
对于函数式接口,我们可以通过Lambda表达式来创建该接口的对象
package com.Thread;
// 1. 定义一个函数式接口
@FunctionalInterface
interface ILike{
void lambda(); //public abstract void lambda(); 默认是抽象方法
}
// 2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("2.普通的实现类");
}
}
public class Lambda {
// 3.静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("3.放在类内部的类,使用static");
}
}
public static void main(String[] args) {
// 调用函数式接口的对象
ILike like1 = new Like();
like1.lambda();
// 调用3静态内部类
ILike like2 = new Like2();
like2.lambda();
// 4.局部内部类
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println("4.局部内部类,放在main方法里面");
}
}
ILike like3 = new Like3();
like3.lambda();
// 5. 匿名内部类,没有类名,必须借助接口或者父类
ILike like4 = new ILike() {
@Override
public void lambda() {
System.out.println("5.匿名内部类,不再需要类名,直接父类/接口的构造函数后面{}跟子类代码");
}
};
like4.lambda();
// 6. Lambda简化,只留下函数的括号还有函数内部代码
ILike like5 = ()->{
System.out.println("6.Lambda简化后,不再需要构造方法名和函数名,根据变量类型来判断的。加个->");
};
like5.lambda();
//参数类型可以省略,多参数要一起省略;只有一条语句才可以省略大括号;一个参数时可以省略括号
}
}
方法 | 说明 |
---|---|
setPriority(int newPriority) | 更改线程优先级 |
static void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程体休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程,别用这个方式 |
boolean isAlive() | 测试线程是否处于活动状态 |
package com.Thread;
//测试stop
//1.建议线程正常停止 ---> 利用次数,不建议死循环
//2.建议使用标志位 ---> 设置一个标志位
//3.不要使用stop或者destroy等过时的方法或者JDK不建议使用的方法
public class StopThread implements Runnable{
//1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("running...Thread" + i++);
}
}
//2.定义一个公开的方法停止线程,转换标志位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
StopThread testThread = new StopThread();
new Thread(testThread).start();
// 次数太少的话,子线程可能抢不到时间片
for (int i = 0; i < 10; i++) {
System.out.println("main" + i);
if(i == 9) {
//调用stop方法切换标志位,让线程停止
testThread.stop();
System.out.println("线程已停止");
}
}
}
}
package com.Thread;
//模拟网络延时:放大问题的发生性
public class Sleep implements Runnable{
private int ticketNumbers = 10;
@Override
public void run() {
while (ticketNumbers > 0) {
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNumbers-- + "张票");
}
}
public static void main(String[] args) {
Sleep ticket = new Sleep();
new Thread(ticket, "小明").start();
new Thread(ticket, "小王").start();
new Thread(ticket, "小红").start();
}
}
package com.Thread;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CountDown {
//模拟倒计时
public static void countDown(int count) throws InterruptedException {
while (count > 0) {
Thread.sleep(1000);
System.out.println(count);
count --;
}
}
//打印系统当前时间
public static void printTime() {
String startTime;
while (true) {
try {
startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
System.out.println(startTime);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
countDown(10);
printTime();
}
}
package com.Thread;
//测试线程礼让
//礼让不一定成功,看CPU心情
public class Yield {
public static void main(String[] args) {
MyYield yield = new MyYield();
new Thread(yield, "a").start();
new Thread(yield, "b").start();
}
}
class MyYield implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始执行");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName() + "线程停止执行");
}
}
package com.Thread;
//测试join方法,想象成插队
public class Join implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程Vip来了" + i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动线程
Join join = new Join();
Thread thread = new Thread(join);
thread.start();
//主线程
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
//迭代第五十次的时候让它插队
if (i == 50) {
thread.join();
}
}
}
}
JDK1.8:
public static enum Thread.State
extends Enum
线程状态。 线程可以处于以下状态之一:
- NEW
尚未启动的线程处于此状态。- RUNNABLE
在Java虚拟机中执行的线程处于此状态。- BLOCKED
被阻塞等待监视器锁定的线程处于此状态。- WAITING
正在等待另一个线程执行特定动作的线程处于此状态。- TIMED_WAITING
正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。- TERMINATED
已退出的线程处于此状态。一个线程可以在给定时间点处于一个状态。 这些状态是不反映任何操作系统线程状态的虚拟机状态。
package com.Thread;
//观察测试线程的状态
public class ThreadState {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("/");
});
//观察状态 NEW
Thread.State state = thread.getState();
System.out.println(state);
//观察启动后 RUN
thread.start();
state = thread.getState();
System.out.println(state);
//只要线程不停止就一直输出状态
while (state != Thread.State.TERMINATED) {
try {
Thread.sleep(100);
//更新线程状态
state = thread.getState();
System.out.println(state);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//线程是一次性用品,死亡后不能再次启动
thread.start();
}
}
package com.Thread;
public class ThreadPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName() + " --> " + Thread.currentThread().getPriority());
MyPriority priority = new MyPriority();
Thread thread = new Thread(priority);
Thread thread1 = new Thread(priority);
Thread thread2 = new Thread(priority);
Thread thread3 = new Thread(priority);
Thread thread4 = new Thread(priority);
Thread thread5 = new Thread(priority);
//先设置优先级再启动
thread.start();
thread1.setPriority(1);
thread1.start();
thread2.setPriority(4);
thread2.start();
thread3.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY = 10
thread3.start();
thread4.setPriority(-1);
thread4.start();
thread5.setPriority(11);
thread5.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " --> " + Thread.currentThread().getPriority());
}
}
优先级低并不意味着不会被调用,只是被调度的概率低,取决于CPU
package com.Thread;
public class Daemon {
public static void main(String[] args) {
God god = new God();
You1 you1 = new You1();
Thread thread = new Thread(god);
thread.setDaemon(true);//默认是false表示是用户线程,正常线程都是用户线程
thread.start();//上帝守护线程启动
new Thread(you1).start();
}
}
class God implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("上帝保佑着你");
}
}
}
class You1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都活得很开心");
}
System.out.println("========== Goodbye,World! ==========");
}
}
当主线程和其他线程结束后,程序就结束了,尽管守护线程是死循环,因为虚拟机不用等待它执行完毕
事实证明,上帝会多保佑你一会
Synchronized
package com.Thread;
//不安全的买票
//线程不安全,有负数
public class UnSafeBuyTicket {
public static void main(String[] args) {
BuyTicket state = new BuyTicket();
new Thread(state, "苦逼的我").start();
new Thread(state, "牛逼的你们").start();
new Thread(state, "可恶的黄牛").start();
}
}
class BuyTicket implements Runnable {
//票
private int ticketNumbers = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNumbers <= 0) {
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNumbers--);
}
}
package com.Thread;
//不安全的取钱
public class UnSafeBank {
public static void main(String[] args) {
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50,"你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.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);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
//判断有没有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够了,取不了");
return;
}
//sleep可以放大问题的发生性
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//卡里余额
account.money = account.money - drawingMoney;
//手上的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
//Thread.currentThread().getName() == this.getName()
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
package com.Thread;
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(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//尽可能小的时间内,大小不会相等,因为可能会有两个或以上的线程同时对一个位置添加元素
System.out.println(list.size());
}
}
同步方法:public synchronized void method(int args) {}
缺陷:若将一个大的方法申明为synchronized将会影响效率
package com.Thread;
//安全的买票
public class SafeBuyTicket {
public static void main(String[] args) {
BuyTicket1 state = new BuyTicket1();
new Thread(state, "苦逼的我").start();
new Thread(state, "牛逼的你们").start();
new Thread(state, "可恶的黄牛").start();
}
}
class BuyTicket1 implements Runnable {
//票
private int ticketNumbers = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNumbers <= 0) {
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNumbers--);
}
}
package com.Thread;
public class SafeBank {
public static void main(String[] args) {
Account1 account = new Account1(1000, "结婚基金");
Drawing1 you = new Drawing1(account, 50,"你");
Drawing1 girlFriend = new Drawing1(account, 100, "girlFriend");
you.start();
girlFriend.start();
}
}
class Account1 {
int money;//余额
String name;//卡名
public Account1(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing1 extends Thread {
final Account1 account;//账户
int drawingMoney;//取多少钱
int nowMoney;//手里的钱
public Drawing1(Account1 account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//如果直接在run加上synchronized修饰,那么监视的对象是this,也就是Drawing1(银行),但我们需要监视的是Account,所以需要用到synchronized块
@Override
public void run() {
//锁的对象即变量,增删改的对象
synchronized (account) {
//判断有没有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够了,取不了");
return;
}
//sleep可以放大问题的发生性
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//卡里余额
account.money = account.money - drawingMoney;
//手上的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
//Thread.currentThread().getName() == this.getName()
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
}
package com.Thread;
import java.util.ArrayList;
import java.util.List;
public class SafeList {
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();
}
//虽然说不加上sleep依然看不到1w,但因为这是并发,主线程并没有被阻塞,for循环跑完之后就直接输出了,而其它线程还没跑完
//这与之前不一样的是,它百分比在每一个位置只添加过一次,只是完成的时间问题而已,而之前的是总有那么几个非要挤在一起
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//尽可能小的时间内,大小不会相等,因为可能会有两个或以上的线程同时对一个位置添加元素
System.out.println(list.size());
}
}
一定要清楚自己监视的对象是谁,也就是增删改的对象
它属于java.util.concurrent下的一个方法,具体功能跟上面的ArrayList+synchronized一样,详细的可以查看源码
package com.Thread;
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型集合
public class JUC {
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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
package com.Thread;
//死锁:多个线程互相抱着对方的需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "灰姑娘");
Makeup makeup1 = new Makeup(1, "白雪公主");
makeup.start();
makeup1.start();
}
}
//口红
class Lipstick {
}
class Mirror {
}
class Makeup extends Thread {
//需要的资源只有一份,用static来保证只有一份
static final Lipstick lipstick = new Lipstick();
static final Mirror mirror = new Mirror();
int choice;
String girlName;
Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
makeup();
}
private void makeup() {
//不交替嵌套,等线程释放资源再使用可以避免死锁,把嵌套的代码取出来即可
if(choice == 0) {
synchronized (lipstick) {
System.out.println(this.girlName + "获得口红的锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (mirror) {
System.out.println(this.girlName + "获得镜子的锁");
}
}
}
else {
synchronized (mirror) {
System.out.println(this.girlName + "获得镜子的锁");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lipstick) {
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
}
package com.Thread;
import java.util.concurrent.locks.ReentrantLock;
public class Lock {
public static void main(String[] args) {
TestLock testLock = new TestLock();
new Thread(testLock, "小明").start();
new Thread(testLock, "小红").start();
new Thread(testLock, "小王").start();
}
}
class TestLock implements Runnable {
private final ReentrantLock lock = new ReentrantLock();
int ticketNumbers = 10;
@Override
public void run() {
while (true) {
try {
lock.lock();
if (ticketNumbers > 0) {
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNumbers-- + "张票");
} else {
break;
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
生产者消费者问题
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度 |
注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常IllegalStateException
一篇文章,让你彻底弄懂生产者–消费者问题 —— 你听___
并发模型“生产者/消费者模式” —> 管程法
package com.Thread;
//测试生产者消费者模型--->利用缓冲区解决:管程法
//生产者 消费者 产品 缓冲区
public class ProducerConsumer {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Producer(container).start();
new Consumer(container).start();
}
}
class Producer extends Thread {
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Production(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 Production extends Thread {
//产品编号
int id;
public Production(int id) {
this.id = id;
}
}
class SynContainer {
//需要一个容器大小
Production[] productions = new Production[10];
//容器计数器
int count = 0;
public synchronized void push(Production production) {
//如果容器满了就需要等待消费者消费
if (count == productions.length) {
//通知消费者消费,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满我们就需要丢入产品
productions[count ++] = production;
//可以通知消费者消费了
this.notifyAll();
}
public synchronized Production pop() {
//判断能否消费
if (count == 0) {
//等待生产者生产,消费者消费
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count --;
Production production = productions[count];
//吃完了,通知生产者生产
this.notifyAll();
return production;
}
}
// The standard idiom for calling the wait method in Java
synchronized (sharedObject) {
while (condition) {
sharedObject.wait();
// (Releases lock, and reacquires on wakeup)
}
// do action based upon condition e.g. take or put into queue
}
package com.Thread;
//测试生产者消费者问题:信号灯法,标志位解决
public class ProducerConsumer1 {
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.play("铠甲勇士播放中");
} else {
this.tv.play("是兄弟就来砍我");
}
}
}
}
//消费者-->观众
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 programme;//表演的节目
boolean flag = true;
//表演
public synchronized void play(String programme) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了," + programme);
//通知观众观看
this.notifyAll();
this.programme = programme;
this.flag = !this.flag;
}
//观看
public synchronized void watch() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:" + programme);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
package com.Thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new ThreadTest());
service.execute(new ThreadTest());
service.execute(new ThreadTest());
service.execute(new ThreadTest());
//2.关用连接
service.shutdown();
}
}
class ThreadTest implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
附属代码
所有资源来源于狂神说的B站投稿视频