多线程
1.概念
可同时进行(电脑cpu仅能单线程,因为速度过快营造出多线程)
2.线程创建
Thread方法
创建线程方式一:设置线程A继承Thread,重写run()方法,创建对象new A,调用A.Start开启线程
//创建线程方式一:继承Thread
//重写run()方法,调用Start开启线程
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程器
for (int i = 0; i < 10; i++) {
System.out.println("我在看代码");
}
}
public static void main(String[] args) {
//main方法,主线程
//创建一个线程对象
TestThread1 testThread1=new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 10; i++) {
System.out.println("我在学习多线程");
}
}
}
网图下载案例
package demo2;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class tupian implements Runnable{
private String url;//网络图片地址
private String name;//保存的文件名
public tupian(String url,String name){
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) {
tupian t1 = new tupian("https://img-s-msn-com.akamaized.net/tenant/amp/entityid/BB1hgG3L.img?w=1920&h=1080&q=60&m=2&f=jpg","1.jpg");
tupian t2 = new tupian("https://img-nos.yiyouliao.com/alph/1935507598b3710e3a60d6e7fdea69be.jpeg?yiyouliao_channel=1536235174142947329_image","2.jpg");
tupian t3 = new tupian("https://img-nos.yiyouliao.com/alph/956b002fbe3c06173dd958f91af8d7f9.jpeg?yiyouliao_channel=1536235174142947329_image","3.jpg");
new Thread(t1).start();new Thread(t2).start();new Thread(t3).start();
//顺序输出123,实际输出231
}
}
//下载器
class webDownloader{
//下载方法
public void downloader(String url,String name){
try {//通过F这个工具类,丢入下载地址跟设定名字
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("io异常,downloader出现问题");
}
}
}
Runnable接口方法
创建线程方式二:设置线程A接口Runnable,重写run()方法,创建对象new A,创建线程对象new Thread(A).start(); (new完顺便调用)
package demo3;
import demo1.TestThread1;
//创建线程方式2:实现runnable接口,重写run()方法,执行
//线程需要丢入runnable接口类,调用start方法
public class TestThread implements Runnable{
@Override
public void run() {
//run方法线程器
for (int i = 0; i < 1000; i++) {
System.out.println("我在看代码");
}
}
public static void main(String[] args) {
//main方法,主线程
//创建runnbale接口的实现类对象
TestThread testThread = new TestThread();
//创建线程对象,通过线程对象类开启我们的线程,代理
Thread thread = new Thread(testThread);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程");
}
}
}
3.并发问题
问题:多个线程操作同一个资源时,线程不安全,数据紊乱
package demo4;
//多个线程同时操作同一个对象
//卖火车票案例
//问题:多个线程操作同一个资源时,线程不安全,数据紊乱
public class TestThread implements Runnable{
//票数
private int tickeNums=10;
@Override
public void run() {
while (true){
if(tickeNums<=0)
{break;}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+"-->"+"拿到了"+tickeNums--+"票");
}
}
public static void main(String[] args) {
TestThread ticket = new TestThread();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛").start();
}
}
4.龟兔赛跑案例
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) {
throw new RuntimeException(e);
}
}
//判断比赛是否结束
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();
}
}
5.静态代理p9
真实对象和代理对象都要实现同一个接口
package demo5;
//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理代理真实角色
//好处:
//代理对象做真实对象做不了的事
//真实对象专注做自己的事
public class a {
public static void main(String[] args) {
new Thread(()->System.out.println("i love you")).start();
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 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("结婚之前");
}
}
6.lamda表达式
理解,只有一个方法时使用,等于直接调用这个方法
各种类表达
public class TestLambdal {
/*推导lambda表达式*/
//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");
}
}
lamda表达式简写
public class TestLambdal2 {
/* static class Love implements ILove{
@Override
public void love(int a) {
System.out.println("i love -->"+a);
}
}*/
public static void main(String[] args) {
/*ILove love = new Love();
love.love(2);*/
//1.lambda表示简化
ILove love =(int a)->{
System.out.println("i lve"+a);
};
//简化1.去除参数类型
love =(a)->{
System.out.println("i lve"+a);
};
//简化2.去除括号
love =a->{
System.out.println("i lve"+a);
};
//简化3.去除花括号,有多行不行简化花括号
love =(a)-> System.out.println("i lve"+a);
//总结:
//lambda表达式只能有一行时简化到花括号,多行时做成代码块
//前提是接口为函数式接口(接口里仅一个方法)
//多个参数也可去掉参数类型,要去掉全去
love.love(5);
}
}
interface ILove{
void love(int a);
}
7.线程
线程停止
package state;
/*测试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("线程该停止了");
}
}
}
}
线程休眠
package state;
import demo4.TestThread;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.SimpleFormatter;
//模拟网络延时:放大问题的发生性
public class TestSleep {
public static void main(String[] args) {
/*try {
tenDown();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}*/
//打印当前系统时间
Date startime = new Date(System.currentTimeMillis());//获取系统当前时间
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format((startime)));
startime=new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException{
int num=10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
线程礼让
礼让:A与B进,A进,A礼让,出来与B再次竞争
package state;
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()+"线程停止执行");
}
}
线程强制执行join
package state;
//jion方法类似于插队
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程join来了"+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);
}
}
}
观测线程状态
死亡之后的线程不能再次启动(可以new一个)
package state;
//观察测试线程的状态
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
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){//只要线程不终止,就一直输出
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
state=thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
线程优先级
PRIORITY---优先级
设置优先级,默认5,范围1~10
优先级高的不一定先执行,几率大
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);
//设置优先级,默认5
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);//MAX=10
t4.start();
// t5.setPriority(-1);
// t5.start();
//
// t6.setPriority(11);
// t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"->"+Thread.currentThread().getPriority());
}
}
守护线程
thread.setDaemon(true);//默认false表示用户线程,正常线程都是用户线程 重点:虚拟机不等待守护线程执行完毕
package state;
//测试守护线程
//上帝守护你
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!------");
}
}
线程同步
并发时
形成条件:队列+锁
不安全案例
package state;
//不安全的买票
//线程安全,有负数
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{
//票
private int ticketNums=10;
boolean flag=true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private void buy() throws InterruptedException{
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
package state;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class UnsafeList {
public static <string> void main(String[] args) {
List<String> list= new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}//线程启动10000个,有重复,最后输出不足10000个
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(list.size());
}
}
同步方法及同步块
package state;
//不安全的买票
//线程安全,有负数
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{
//票
private int ticketNums=10;
boolean flag=true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
//synchronized 同步方法,锁的this
private synchronized void buy() throws InterruptedException{
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList;
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list =new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(list.size());
}
}
8.锁
死锁
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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) {
throw new RuntimeException(e);
}
}
//化妆,互相持有对方的锁,就是需要对方的资源
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;
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 tickNums=10;
//定义lock锁
private ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while(true){
try {
lock.lock();//加锁
if (tickNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(tickNums--);
}else{
break;
}
}finally {
//解锁
lock.unlock();
}
}
}
}
9.线程协作
生产者和消费者问题
解决方法1.
//测试生产者消费者模型--》利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
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++) {
container.push(new chicken(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 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(count==chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
chickens[count]=chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized chicken pop(){
//判断是否消费
if (count==0){
//等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
chicken chicken= chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
解决方法2.新号灯法
//测试生产者消费者问题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) {
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{
//演员表演,观众等待
//观众观看,演员等待
String voice;//表演的节目
boolean flag=true;
//表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("演员表演了:"+voice);
//通知观众观看
this.notifyAll();//通知唤醒
this.voice=voice;
this.flag=!this.flag;
}
//观看
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag=!this.flag;
}
}
10.线程池
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());
}
}
11.总结
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结线程创建
public class ThreadNew {
public static void main(String[] args) {
Mythread mythread = new Mythread();
mythread.start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
Integer integer= null;
try {
integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
//1.继承Thread类
class Mythread extends Thread{
@Override
public void run(){
System.out.println("MyThread1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
//3.实现callable接口
//class MyThread3 implements Callable<Integer>{
// @Override
// public Integer call() throws Exception {
// System.out.println("MyThread3");
// return 100;
// }
//}