Java多线程详解多线程龟兔赛跑实力及实现Callable接口
Posted 轻狂书生han
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程详解多线程龟兔赛跑实力及实现Callable接口相关的知识,希望对你有一定的参考价值。
抢票
package com.xiancheng.demo01;
//多个线程透视操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况系啊,线程不安全,数据紊乱
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();
}
}
案例:龟兔赛跑
1.首先来个赛道距离,然后要离重点越来越近
2.判断比赛是否结束
3.打印出胜利者
4.龟兔赛跑开始
5.故事中是乌龟赢得,兔子需要睡觉,所以我们来模拟兔子睡觉
6.终于乌龟赢得比赛
package com.xiancheng.demo01;
//模拟龟兔赛跑
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(10);
} 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方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行:Future
result1 = ser.submit(t1); - 获取结果:boolean ri = result.get();
- 关闭服务:ser.shutdownNow();
package com.xiancheng.demo02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式三,实现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();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable testThread1 = new TestCallable("https://imgoss.douyucdn.cn/bj/yuba/default/2019/12/20/201912200221045779841615885.jpg","1.jpg");
TestCallable testThread2 = new TestCallable("https://imgoss.douyucdn.cn/bj/yuba/default/2021/03/26/202103262200428765268485985.jpg","2.jpg");
TestCallable testThread3 = new TestCallable("https://img.douyucdn.cn/data/yuba/default/2019/08/18/201908182138163129577786480.200x0.jpg","3.jpg");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = ser.submit(testThread1);
Future<Boolean> r2 = ser.submit(testThread2);
Future<Boolean> r3 = ser.submit(testThread3);
//获取结果
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();
}
}
//下载器
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方法出现问题");
}
}
}
静态代理
package com.xiancheng.demo02;
//静态代理模式总结
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//好处
//代理对象可以做很多真实对象做不了的事
//真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
new Thread( ()-> System.out.println("我爱你") ).start();
new WeddingCompany(new You()).HappyMarry();
You you = new You();//你要结婚
//WeddingCompany weddingCompany = new WeddingCompany(new You());
//weddingCompany.HappyMarry();
}
}
interface Marry{
//人间四大喜事
//久旱逢甘霖
//他乡遇故知
//洞房花烛夜
//金榜题名时
void HappyMarry();
}
//真实角色,你去结婚
class You implements Marry{
@Override
public void HappyMarry(){
System.out.println("秦老师要结婚了,敲开心");
}
}
//代理角色,帮你结婚
class WeddingCompany implements Marry{
//代理谁--》真实目标角色
private Marry targer;
public WeddingCompany(Marry targer) {
this.targer = targer;
}
@Override
public void HappyMarry() {
before();
this.targer.HappyMarry();//这就是真实对象
after();
}
private void after() {
System.out.println("结婚之后,收尾款");
}
private void before() {
System.out.println("结婚之前,布置现场");
}
}
以上是关于Java多线程详解多线程龟兔赛跑实力及实现Callable接口的主要内容,如果未能解决你的问题,请参考以下文章