1.gc线程,用于清理垃圾
线程的三种创建方式
继承Thread类
基本代码
package com.zhang.Thread;
//创建线程方式:继承Thread类,重写run()方法,调用start开启线程
//总结:注意,线程开启不一定立即执行,由CPU调度执行
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码---"+i);
}
}
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);
}
}
}
commons-io工具类库
- 百度搜“commons-io”,进Apache官网下载
- 将“commons-io-2.11.0.jar”复制,在IDEA中新建com.lib包,选中lib,粘贴“commons-io-2.11.0.jar”。右击lib,选择“Add as Library”-“OK”,添加成功。(在IDEA-File-Project Structure-Libraries中可以查看到lib包的目录)
网图下载案例
package com.zhang.Thread;
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){//快捷键“TT2”
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("https://pics1.baidu.com/feed/ac345982b2b7d0a2ace78386f76f940f4b369a02.jpeg?token=65b8ddfe60e56339e02a4572b041faa0","xian1.jpg");
TestThread2 t2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202107%2F28%2F20210728102537_c4005.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655436924&t=9646bc8304176103e3fcbfd5c2461995","xian2.jpg");
TestThread2 t3 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201910%2F20%2F20191020203635_AnQaz.thumb.400_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655437048&t=1a7fd5a73a6b1bcb7f8485810e46c336","xian3.jpg");
t1.start();
t2.start();
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方法出现问题");
}
}
}
实现Runnable接口(推荐使用)
基本代码
package com.zhang.Thread;
//创建线程方式2:实现Runnable接口,重写run()方法,执行线程需要丢入Runnable接口的实现类,调用start()方法
public class TestThread3 implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; 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 < 20; i++) {
System.out.println("我在学习多线程---"+i);
}
}
}
网图下载案例重写对比
package com.zhang.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread2 implements Runnable{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread2(String url,String name){//快捷键“TT2”
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("https://pics1.baidu.com/feed/ac345982b2b7d0a2ace78386f76f940f4b369a02.jpeg?token=65b8ddfe60e56339e02a4572b041faa0","xian1.jpg");
TestThread2 t2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202107%2F28%2F20210728102537_c4005.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655436924&t=9646bc8304176103e3fcbfd5c2461995","xian2.jpg");
TestThread2 t3 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201910%2F20%2F20191020203635_AnQaz.thumb.400_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655437048&t=1a7fd5a73a6b1bcb7f8485810e46c336","xian3.jpg");
new Thread(t1).start();
new Thread(t2).start();
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()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
并发问题
package com.zhang.Thread;
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread4 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);//200毫秒,0.2秒
} 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();
}
}
龟兔赛跑
package com.zhang.Thread;
//模拟龟兔赛跑
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();
}
}
实现Callable接口
网图下载案例重写对比
package com.zhang.Thread2;
import com.zhang.Thread.TestThread2;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式3:实现Callable接口
/*
callable的好处
1.可以定义返回值
2.可以抛出异常
3.
*/
public class TestCallable implements Callable<Boolean>{
private String url;//网络图片地址
private String name;//保存的文件名
public TestCallable(String url,String name){//快捷键“TT2”
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 t1 = new TestCallable("https://pics1.baidu.com/feed/ac345982b2b7d0a2ace78386f76f940f4b369a02.jpeg?token=65b8ddfe60e56339e02a4572b041faa0","xian1.jpg");
TestCallable t2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fblog%2F202107%2F28%2F20210728102537_c4005.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655436924&t=9646bc8304176103e3fcbfd5c2461995","xian2.jpg");
TestCallable t3 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201910%2F20%2F20191020203635_AnQaz.thumb.400_0.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655437048&t=1a7fd5a73a6b1bcb7f8485810e46c336","xian3.jpg");
//创建执行服务:
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.shutdown();
}
}
//下载器
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.zhang.Thread2;
//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//好处:
//代理对象可以做很多真实对象做不了的事情
//真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
// new Thread(new Runnable() {
// @Override
// public void run() {
//
// }
// }).start();
new Thread(()-> System.out.println("我爱你")).start();//用lamda表达式实现Runnable接口
// WeddingCompany weddingCompany = new WeddingCompany(new You());
// weddingCompany.HappyMarry();
new WeddingCompany(new You()).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表达式
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。对于函数式接口,我们可以通过Lamda表达式来创建该接口的对象。
package com.zhang.lambda;
/*
推导Lambda表达式
*/
public class TestLambda {
//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();//用接口创建对象(创建接口对象)(接口new了一个实现类)
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表达式
package com.zhang.lambda;
public class TestLambda2 {
public static void main(String[] args) {
ILove love = (int a) -> {
System.out.println("i love you——>"+a);
};
love.Love(520);
}
}
interface ILove{
void Love(int a);
}
(CTRL+SHIFT+/ 给多行代码添加注释)
Lambda表达式简化
package com.zhang.lambda;
public class TestLambda2 {
public static void main(String[] args) {
ILove love = null;
/* //1.Lambda表达式简化
ILove love = (int a) -> {
System.out.println("i love you——>"+a);
};
//简化1:参数类型
love = (a) -> {
System.out.println("i love you——>"+a);
};*/
//简化2:简化括号
/* love = a -> {
System.out.println("i love you——>"+a);
};*/
//简化3:去掉花括号
love = a -> System.out.println("i love you——>"+a);
//总结:
//Lambda表达式只能有一行代码的情况下才能简化成一行,如果有多行,那么就用代码块包裹。(即,用花括号)
//前提是接口为函数式接口
//多个参数,也可以去掉参数类型,要去掉就都去掉,必须加上括号
love.Love(521);
}
}
interface ILove{
void Love(int a);
}