多线程
文章目录
线程开启的三种方式:
继承Thread类和实现Runnable接口(重点)、实现callable接口(了解)
继承Thread:
package pers.lwx.Thread;
/**
* @program: study
* @description: 开启线程
* 1.创建线程的方式一:继承Thread类,重写run方法,调用start开启线程
* 2.注意:线程开启不一立即执行,由cpu调度执行
* @author: codelwx
* @create: 2021-01-06 11:37
**/
public class ThreadDemo extends Thread {
@Override
public void run() {
//run方法线程体
for(int i = 0;i <= 200;i++){
System.out.println("我是线程!");
}
}
//main主线程
public static void main(String[] args) {
//创建一个线程对象
ThreadDemo td = new ThreadDemo();
//调用start()方法开启线程
td.start();
for(int j = 0;j <= 2000;j++){
System.out.println("我是方法体");
}
}
}
实现Runnable接口
package pers.lwx.Thread;
/**
* @program: study
* @description: 开启线程:
* 1.开启线程方式二:实现Runnable接口,重写run方法,调用start方法开启线程
* @author: codelwx
* @create: 2021-01-11 14:48
**/
public class RunnableDemo implements Runnable {
@Override
public void run() {
//run方法线程体
for (int i = 0; i <= 200; i++) {
System.out.println("我是线程!");
}
}
//main主线程
public static void main(String[] args) {
//创建实例对象
RunnableDemo runnableDemo = new RunnableDemo();
//创建线程对象,通过线程对象开启线程,实现代理
//Thread td = new Thread(runnableDemo);
//调用start()方法开启线程
//td.start();
new Thread(runnableDemo).start();
for (int j = 0; j <= 2000; j++) {
System.out.println("我是方法体");
}
}
}
小结
实现callable接口
实现Callable
package pers.lwx.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
/**
* @program: study
* @description: 实现callable接口
* @author: codelwx
* @create: 2021-01-11 17:14
**/
public class callableDemo implements Callable {
private String url;//下载路径
private String name;//下载文件名
public callableDemo(String url,String name){
this.url = url;
this.name = name;
}
@Override
public Boolean call() {
WebDownloader01 wdl = new WebDownloader01();
wdl.webDownloadFile(url,name);
System.out.println("当前下载图片名称:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadDownloadFile thread01 = new ThreadDownloadFile("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9KZExrRUk5c1pmZmVuSTJXM085enpzaWJVUldLWmRLS25qbTVxcmliaWFvRllnbUNXeTQxU2ljV1JzdERwaWNKdHZuaWJQNU5zaWM0VUJZSlhESGxpYzg5U0NwZmFRLzY0MA?x-oss-process=image/format,png","a1.jpg");
ThreadDownloadFile thread02 = new ThreadDownloadFile("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9KZExrRUk5c1pmZmVuSTJXM085enpzaWJVUldLWmRLS24ydGRlVlFDaGM1bFR5b1NNZkJ0bmJ3ZVlGZEhuZXE3UUZqa3JKZlp4aWJmMHlpYjdRMXF1VWNmdy82NDA?x-oss-process=image/format,png","a2.jpg");
ThreadDownloadFile thread03 = new ThreadDownloadFile("https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X3BuZy9KZExrRUk5c1pmZmVuSTJXM085enpzaWJVUldLWmRLS25RS2liY3Q3ZGlhaWFrUG5rcE5EaWNGZ0hhVGx6bmNNMmphWmcxaWJnSlVwN0VhdGpQakdSZGljaWF0ZGNRLzY0MA?x-oss-process=image/format,png","a3.jpg");
//创建执行服务
ExecutorService exeser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = (Future<Boolean>) exeser.submit(thread01);
Future<Boolean> r2 = (Future<Boolean>) exeser.submit(thread02);
Future<Boolean> r3 = (Future<Boolean>) exeser.submit(thread03);
//获取结果
Boolean rs1 = r1.get();
Boolean rs2 = r2.get();
Boolean rs3 = r3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
//关闭服务
exeser.shutdown();
}
}
class WebDownloader01{
public void webDownloadFile(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,webDownloader方法出现问题");
}
}
}
静态代理模式:
package pers.lwx.other;
/**
* @program: study
* @description: 静态代理模式对比线程
* @author: codelwx
* @create: 2021-01-11 18:10
**/
public class StaticProxy {
public static void main(String[] args) {
new Thread(()-> System.out.println("我爱你")).start();
WiddingMarry widdingMarry = new WiddingMarry(new you());
widdingMarry.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实角色
class you implements Marry{
@Override
public void HappyMarry() {
System.out.println("新婚快乐");
}
}
//代理对象,代理完成结婚
class WiddingMarry implements Marry{
private Marry target;
public WiddingMarry(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表达式
package pers.lwx.Lamda;
/**
* @program: study
* @description: lamda表达式
* @author: codelwx
* @create: 2021-01-11 19:01
**/
public class LamdaDemo {
//静态内部类
// static class Like implements ILike {
// @Override
// public void love(int a) {
// System.out.println("我爱你:"+a);
// }
// }
public static void main(String[] args) {
//局部内部类
// class Like implements ILike {
// @Override
// public void love(int a) {
// System.out.println("我爱你:" + a);
// }
// }
//匿名内部类
// ILike ilike = new ILike() {
// @Override
// public void love(int a) {
// System.out.println("我爱你:" + a);
// }
// };
// ilike.love(5);
//lamda表达式:简化
ILike ilike = (int a) -> {
System.out.println("我爱你:" + a);
};
ilike.love(5);
//简化参数类型
ILike ilike1 = (a) -> {
System.out.println("我爱你:" + a);
};
ilike1.love(6);
//简化括号
ILike ilike2 = a -> {
System.out.println("我爱你:" + a);
};
ilike2.love(7);
//去掉花括号
ILike ilike3 = a -> System.out.println("我爱你:" + a);
ilike3.love(7);
//总结:1.lamda表达式只有表达一行时可以去掉花括号
//2.前提是接口为函数式接口
//3.多个参数去掉参数类型时要一同去掉
}
}
interface ILike {
void love(int a);
}
//外部类
//class Like implements ILike {
// @Override
// public void love(int a) {
//
// }
//}
线程状态:
停止线程:
package pers.lwx.Thread;
/**
* @program: study
* @description: 停止线程
* @author: codelwx
* @create: 2021-01-11 20:14
**/
public class StopThread implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run..Thread:"+i++);
}
}
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
StopThread stopThread = new StopThread();
new Thread(stopThread).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main:"+i);
if(i == 900){
stopThread.stop();
System.out.println("线程停止了");
}
}
}
}
sleep
package pers.lwx.ThreadState;
/**
* @program: study
* @description: 模拟网络延迟:放大问题的发生性
* @author: codelwx
* @create: 2021-01-11 20:34
**/
public class SleepDemo01 implements Runnable {
private int ticketNum = 10;
@Override
public void run() {
while (true) {
if (ticketNum <= 0) {
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":抢的第" + ticketNum--);
}
}
public static void main(String[] args) {
SleepDemo01 tickets = new SleepDemo01();
new Thread(tickets, "小明").start();
new Thread(tickets, "老师").start();
new Thread(tickets, "黄牛").start();
}
}
package pers.lwx.ThreadState;
/**
* @program: study
* @description: 倒计时
* @author: codelwx
* @create: 2021-01-11 20:36
**/
public class SleepDemo02 implements Runnable {
@Override
public void run() {
int i = 10;
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i--);
if (i <= 0) {
break;
}
}
}
public static void main(String[] args) {
SleepDemo02 sleepDemo02 = new SleepDemo02();
new Thread(sleepDemo02).start();
}
}
package pers.lwx.ThreadState;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @program: study
* @description: 打印当前时间
* @author: codelwx
* @create: 2021-01-11 20:41
**/
public class SleepDemo03{
public static void main(String[] args) throws InterruptedException {
Date date = new Date(System.currentTimeMillis());
while(true){
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
Thread.sleep(1000);
date = new Date(System.currentTimeMillis());
}
}
}
yield
join
package pers.lwx.ThreadState;
/**
* @program: study
* @description: join阻塞测试
* @author: codelwx
* @create: 2021-01-12 14:46
**/
public class JoinDemo implements Runnable {
public static void main(String[] args) throws InterruptedException {
JoinDemo joinDemo = new JoinDemo();
Thread thread = new Thread(joinDemo);
for (int i = 0; i < 100; i++) {
if (i == 50) {
thread.start();
thread.join();
}
System.out.println("main:" + i);
}
}
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("vip占用" + i);
}
}
}
观测线程状态
package pers.lwx.Thread;
import static javafx.scene.input.KeyCode.T;
/**
* @program: study
* @description: 观测线程状态
* @author: codelwx
* @create: 2021-01-12 15:08
**/
public class StateDemo {
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(10);
state = thread.getState();
System.out.println(state);//输出线程状态
}
}
}
线程优先级
package pers.lwx.Thread;
/**
* @program: study
* @description: 线程优先级
* @author: codelwx
* @create: 2021-01-12 15:29
**/
public class ThreadPriorityDemo {
public static void main(String[] args) {
//主线程信息
System.out.println(Thread.currentThread().getName()+"-->+"+Thread.currentThread().getPriority());
ThreadPriority threadPriority = new ThreadPriority();
Thread t1 = new Thread(threadPriority, "1");
Thread t2 = new Thread(threadPriority, "2");
Thread t3 = new Thread(threadPriority, "3");
Thread t4 = new Thread(threadPriority, "4");
Thread t5 = new Thread(threadPriority, "5");
Thread t6 = new Thread(threadPriority, "6");
//设置线程优先级
t1.setPriority(1);
t2.setPriority(2);
t3.setPriority(3);
t4.setPriority(4);
t5.setPriority(5);
t6.setPriority(Thread.MAX_PRIORITY);
//开启线程
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
}
static class ThreadPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
}
守护线程
package pers.lwx.Thread;
/**
* @program: study
* @description: 守护线程
* @author: codelwx
* @create: 2021-01-12 18:01
**/
public class DaemonDemo {
public static void main(String[] args) {
You you = new You();
Gold gold = new Gold();
Thread thread = new Thread(gold);
thread.setDaemon(true);//默认是false表示用户线程,正餐的线程都是用户线程。。。
thread.start();//上地守护线程启动
new Thread(you).start();//用户线程启动
}
}
class You implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程启动" + i);
}
System.out.println("======over=======");
}
}
class Gold implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("上帝保佑你");
}
}
}
线程同步
三大不安全案例
不安全的银行取钱
package pers.lwx.syn;
/**
* @program: study
* @description: 不安全的银行取钱
* @author: codelwx
* @create: 2021-01-14 14:38
**/
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "结婚基金");
Drawing myself = new Drawing(account, 50, "本人");
Drawing girlFriend = new Drawing(account, 100, "女朋友");
myself.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() {
//同步代码块,默认锁的this(本身)。锁的是变化的量,需要增删改的对象
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);
//Thread.currentThread().getName() = this.getName();
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
}
运行结果:
结婚基金余额为:50
本人手里的钱50
女朋友钱不够,取不了
不安全的买票
package pers.lwx.syn;
/**
* @program: study
* @description: 不安全的买票
* @author: codelwx
* @create: 2021-01-14 14:21
**/
public class UnsafeBuyTicket implements Runnable {
private int ticketNum= 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(ticketNum <= 0){
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
}
public static void main(String[] args) {
UnsafeBuyTicket ubt = new UnsafeBuyTicket();
new Thread(ubt,"张三").start();
new Thread(ubt,"李四").start();
new Thread(ubt,"王五").start();
}
}
运行结果:
张三拿到10
王五拿到9
王五拿到8
王五拿到7
李四拿到6
李四拿到5
王五拿到4
王五拿到3
张三拿到2
王五拿到1
不安全的线程
package pers.lwx.syn;
import java.util.ArrayList;
import java.util.List;
/**
* @program: study
* @description: 不安全的线程
* @author: codelwx
* @create: 2021-01-14 15:30
**/
public class UnSafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(1000);
System.out.println(list.size());
}
}
运行结果:
10000
死锁
package pers.lwx.syn;
import java.awt.*;
/**
* @program: study
* @description: 死锁测试案例
* 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
* @author: codelwx
* @create: 2021-01-15 13:50
**/
public class DeadLockDemo {
public static void main(String[] args) {
MakeUp g1 = new MakeUp(1, "白雪公主");
MakeUp g2 = new MakeUp(0, "灰姑娘");
g1.start();
g2.start();
}
}
//口红
class LipsStick {
}
//镜子
class Mirror {
}
class MakeUp extends Thread {
//需要的资源只要一份,用static保证只有一份
static LipsStick lipsStick = new LipsStick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用化妆品的人
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 (lipsStick) {
System.out.println(this.girlName + "获得口红的锁");
Thread.sleep(2000);
}
synchronized (mirror) {
System.out.println(this.girlName + "获得镜子的锁");
}
} else {
synchronized (mirror) {
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(1000);
}
synchronized (lipsStick) {
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
Lock锁
ReentrantLock:可重入锁
package pers.lwx.syn;
import java.util.concurrent.locks.ReentrantLock;
/**
* @program: study
* @description: 锁的测试案例
* @author: codelwx
* @create: 2021-01-15 14:30
**/
public class LockDemo{
public static void main(String[] args) {
LockDemo01 lockDemo = new LockDemo01();
new Thread(lockDemo).start();
new Thread(lockDemo).start();
new Thread(lockDemo).start();
}
}
class LockDemo01 implements Runnable{
int ticketNums = 10;
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();
}
}
}
}
线程协作(问题:生产者消费模式)
管道法
package pers.lwx.syn.生成者消费者问题;
/**
* @program: study
* @description: 测试:生成者消费者模型-》利用缓冲区解决:管程法
* 生产者 消费者 产品 缓冲区
* @author: codelwx
* @create: 2021-01-15 14:48
**/
public class TestPC {
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++) {
System.out.println("生产了"+i+"只鸡");
container.push(new Chicken(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 Chicken {
int id;//编号
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer {
//容器大小
Chicken[] chickens = new Chicken[10];
//容器计数
int count = 0;
public synchronized void push(Chicken chicken){
//如果容器满了,等待消费者消费
if(chickens.length == count){
//通知消费者消费,等待生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//没有满,生产产品
chickens[count] = chicken;
count++;
//可以通知消费者消费
this.notify();
}
public synchronized Chicken pop(){
//判断是否消费
if(count == 0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
信号灯法
package pers.lwx.syn.生成者消费者问题;
/**
* @program: study
* @description: 信号灯法
* @author: codelwx
* @create: 2021-01-15 20:24
**/
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.flag = !this.flag;
this.voice = voice;
}
//观看
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 pers.lwx.syn.线程池;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @program: study
* @description: 线程池
* @author: codelwx
* @create: 2021-01-15 20:50
**/
public class TestPool {
public static void main(String[] args) {
//1.创建线程,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.submit(new MyPool());
service.submit(new MyPool());
service.submit(new MyPool());
service.submit(new MyPool());
//2.关闭连接
service.shutdown();
}
}
class MyPool implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}