基础知识
一:run()和start()区别
1、调用start():
主线程和子线程同时开始进行,交替进行。(并发)
2、调用run():
要执行了子线程,执行完毕后才会执行主线程。
二:extends Thread 和 implements Runnable 区别
三、静态代理模式
静态代理模式总结:
1、真实对象和代理对象都要实现同一个接口
2、代理对象代理真实角色
好处:
1、代理对象可以做很多真实对象做不了的事情
2、真实对象专注做自己的事情
//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理对象代理真实角色
/*
好处:
1、代理对象可以做很多真实对象做不了的事情
2、真实对象专注做自己的事情
* */
public class StacticProxy {
public static void main(String[] args) {
You you = new You();
//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 after() {
System.out.println("结婚之后,收尾款");
}
private void before() {
System.out.println("结婚之前,布置现场");
}
}
四、Lambda表达式
lambda表达式的推导
/*
推导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");
}
}
like = new Like3();
like.lambda();
//5.匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("i like lambda4");
}
};
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");
}
}
lambda表达式总结
public class TestLambda2 {
public static void main(String[] args) {
//1.lambda表示简化
Ilove love = (int a) -> {
System.out.println("i love you -->" + a);
};
//简化1.去掉参数类型
love = (a)-> {
System.out.println("i love you -->" + a);
};
//2.简化2.简化括号
love = a-> {
System.out.println("i love you -->" + a);
};
//3.简化3:去掉花括号
love = a-> System.out.println("i love you -->" + a);
//总结:
//lambda表达式只能有一行代码的情况下才能简化成为一行,多行需要代码块
//前提接口为函数式接口(只有一个方法)
//多个参数也可以去掉参数类型,要去掉就都去掉,必须加括号()
love.love(520);
}
}
interface Ilove{
void love(int a);
}
五、线程五大状态
线程强行停止的方法
使用标志位
//测试stop
//1.建议线程正常停止--->利用次数,不建议死循环,
//2.建议使用标志位--->设置一个标志位
//3.不要使用stop或者destroy等过时或者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("线程该停止了");
}
}
}
}
六、线程休眠
实现延时可以发现问题
多个线程操作同一对象,会出现并发问题。
模拟网络延迟:放大问题的发生性。
import com.kuang.demo01.TestThread4;
//模拟网络延迟:放大问题的发生性
public class TestSleep 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) {
TestSleep ticket = new TestSleep();
new Thread(ticket, "小明").start();
new Thread(ticket, "老师").start();
new Thread(ticket, "黄牛").start();
}
}
模拟倒计时
//模拟倒计时
public class TestSleep2 {
public static void main(String[] args) throws InterruptedException {
tenDown();
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
}
每秒打印时间
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
//模拟倒计时
public class TestSleep2 {
public static void main(String[] args) throws InterruptedException {
//打印当前系统时间
Date startTime = new Date(System.currentTimeMillis()); //获取系统当前时间
while (true){
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis()); //更新当前时间
}
}
}
七、线程礼让
//测试礼让教程
//礼让不一定成功,看cpu心情
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() + "线程停止执行");
}
}
八、线程强制执行
少使用,会让线程阻塞。
import java.util.function.DoubleToIntFunction;
//测试join方法:想象为插队
public class TestJoin 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 {
//启动我们的线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 1000; i++) {
if (i == 200) {
//插队
thread.join();
}
System.out.println("main" + i);
}
}
}
九、观测线程状态
import java.sql.SQLOutput;
//观察测试线程的状态
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(1000);
state = thread.getState(); //更新线程状态
System.out.println(state); //输出状态
}
}
}
十、线程的优先级
//测试线程优先级
public class TestPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
//先设置优先级,再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(8);
t5.start();
t6.setPriority(7);
t6.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!=====-");
}
}
十二、线程同步机制
形成条件:队列 + 锁
方法里需要修改内容才需要锁
并发:同一个对象被多个线程同时操作
三大不安全案例
1、线程不安全:有负数
不安全解决方法:用synchronized关键词锁方法
//修改后:private synchronized void buy() throws InterruptedException
//不安全的买票
//线程不安全,有负数
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{
//票
boolean flag = true; //外部停止方式
private int ticketNums = 10;
@Override
public void run() {
//买票
while(flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//修改后:private synchronized void buy() throws InterruptedException
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
//模拟延时
Thread.sleep(1000);
//买票
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);
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 -= drawingMoney;
nowMoney += drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
不安全解决方法:用synchronized块,可以锁任何对象
因为synchronized默认锁 this(类本身UnsaferBank)
//不安全的取钱
//两个人去银行取钱,账户
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);
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;
}
//sleep可以放大问题发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money -= drawingMoney;
nowMoney += drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
}
线程不安全的集合
不同线程对list同一个空间进行更改,会导致覆盖。
import java.util.ArrayList;
import java.util.List;
//集合线程不安全
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(1000);
System.out.println(list.size()); //结果为:9999
}
}
用synchronized锁块
import java.util.ArrayList;
import java.util.List;
//集合线程不安全
public class UnsafeList {
public 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(1000);
System.out.println(list.size());
}
}
十三、死锁
死锁例子及解决方法
//死锁:多个线程互相抱着对方需要的资源,然后互相僵持
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0, "灰姑娘");
Makeup g2 = new Makeup(1, "白雪公主");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
//化妆
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
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 (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锁
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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(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++) {
try {
container.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
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++) {
try {
System.out.println("消费了-->" + container.pop().id + "只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//产品
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) throws InterruptedException {
//容器满了,等待消费者消费
if (count == chickens.length) {
//通知消费者消费,生产者等待
this.wait();
}
//没有满,丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop() throws InterruptedException {
//判断能否消费
if (count == 0) {
//等待生产者生产,消费者等待
this.wait();
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
信号灯法:设立标志位
import netscape.security.UserTarget;
//测试生产者消费者问题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) {
try {
this.tv.play("喵喵喵播放中");
} catch (InterruptedException e) {
e.printStackTrace();
}
} else{
try {
this.tv.play("汪汪汪播放中");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//消费者-->观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
tv.watch();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//产品-->节目
class TV{
//演员表演,观众等待 true
//观众观看,演员等待 false
String voice; //表演的节目
boolean flag = true;
//表演
public synchronized void play(String voice) throws InterruptedException {
if (!flag) {
this.wait();
}
System.out.println("演员表演了:" + voice);
//通知观众观看
this.notifyAll();
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch() throws InterruptedException {
if (flag) {
this.wait();
}
System.out.println("观看了:" + voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
十六、线程池
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());
}
}
线程实现
⭐继承Thread类
extends Thread。
重写run()方法。
不推荐使用
TestThread1
//创建线程方式一:继承Thread类,重写run()方法。调用start()开启线程
//总结:线程开启不一定立即执行,由cpu调度执行
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码---" + i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程---" + i);
}
}
}
TestThread2
网图下载小例子
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
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();
try {
webDownloader.downloader(url, name);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下载了文件名为“:" + name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://profile.csdnimg.cn/A/A/3/1_qq_42467009", "1.jpg");
TestThread2 t2 = new TestThread2("https://img-home.csdnimg.cn/images/20210114022819.png", "2.jpg");
TestThread2 t3 = new TestThread2("https://img-home.csdnimg.cn/images/20210114022831.png", "3.jpg");
t1.start();
t2.start();
t3.start();
}
}
//下载器
class WebDownloader {
//下载方法
public void downloader(String url, String name) throws IOException {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
⭐实现Runnable接口
implements Runnable。
重写run()方法。
推荐使用这种。
把 runnable接口 的参数扔进 new Thread 里
TestThread3
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法。
public class TestThread3 implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 10; 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 < 10; i++) {
System.out.println("我在学习多线程---" + i);
}
}
}
TestThread2
package com.kuang.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread2 implements Runnable {
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();
try {
webDownloader.downloader(url, name);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下载了文件名为“:" + name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://profile.csdnimg.cn/A/A/3/1_qq_42467009", "1.jpg");
TestThread2 t2 = new TestThread2("https://img-home.csdnimg.cn/images/20210114022819.png", "2.jpg");
TestThread2 t3 = new TestThread2("https://img-home.csdnimg.cn/images/20210114022831.png", "3.jpg");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
//下载器
class WebDownloader {
//下载方法
public void downloader(String url, String name) throws IOException {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
初识并发问题
实现多个线程操作同一对象,出现并发问题。
//多个线程同时操作同一个对象
//买火车票例子
//发现问题:多个线程操作同一个资源情况下,线程不安全,数据紊乱。
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();
}
}
龟兔赛跑
//模拟龟兔赛跑
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;
} else {
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接口
了解即可。
implements Callable<…>
重写call()方法。
Callable好处:
1、可以定义返回值。
2、可以抛出异常。
//线程创建方式三:实现callable接口
/*
Callable好处:
1、可以定义返回值。
2、可以抛出异常。
* */
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();
try {
webDownloader.downloader(url, name);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("下载了文件名为“:" + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://profile.csdnimg.cn/A/A/3/1_qq_42467009", "1.jpg");
TestCallable t2 = new TestCallable("https://img-home.csdnimg.cn/images/20210114022819.png", "2.jpg");
TestCallable t3 = new TestCallable("https://img-home.csdnimg.cn/images/20210114022831.png", "3.jpg");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
//获取结果
//System.out.println(rs1)的结果都是 true
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
//关闭服务:
ser.shutdownNow();
}
}
//下载器
class WebDownloader {
//下载方法
public void downloader(String url, String name) throws IOException {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}