多线程概述
Process --- 进程
Thread --- 线程
-
线程就是独立的执行路径;
-
在程序执行时,即是没有自己创建线程,后台也会有多个线程,如主线程,gc线程等;
-
main()称之为主线程,为系统的入口,用于执行整个程序;
-
在一个进程中,如果开辟了多个线程,线程的运行是由调度器安排调度,调度器与操作系统紧密相关,先后顺序是不能人为干扰的;
-
对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制;
-
线程会带来额外的开销,如cpu调度时间,并发控制开销;
-
每个线程在自己的工作内存交互,内存操作不当会存在数据不一致;
线程的创建
三种创建方式:
-
继承Thread类
-
实现Runnable接口(重点)
-
实现Callable接口
-
有返回值
-
可以抛出异常
-
//创建线程一:继承Thread类 public class TestThread1 extends Thread{ @Override public void run(){ //run方法线程体 for(int i = 1; i< 21; i++){ System.out.println("我在看多线程!" + i); } } public static void main(String[] args){ //main线程,主线程 //创建线程对象 TestThread1 testTread1 = new TestThread1(); //调用start()方法开启线程 testTread1.start(); for(int i = 1; i< 21; i++){ System.out.println("主线程!"+ i); } } }
//创建线程方式二:实现runnable接口 public class TestThread2 implements Runnable{ @Override public void run(){ //run方法线程体 for(int i = 1; i< 21; i++){ System.out.println("我在看多线程!" + i); } } public static void main(String[] args){ //创建runnable接口的实现类对象 TestThread2 testThread2 = new TestThread2(); //创建线程对象,通过线程对象来开启我们的线程,代理 new Thread(testThread2).start(); for(int i = 1; i< 21; i++){ System.out.println("主线程!"+ i); } } }
总结:
-
线程开启不一定立即执行,由cpu调度执行。
练习
练习1: 实现多线程网图同步下载
重写run(),调用start()
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; //练习,实现多线程同步下载图片 public class TestThread1 implement Runnable{ private String url; private String name; public TestThread1(String url,String name){ this.url = url; this.name = name; } @Override public void run() { WebDOwnLoder webDOwnLoder = new WebDOwnLoder(); webDOwnLoder.downloder(url,name); System.out.println("下载了文件名为:"+name+"的文件!"); } public static void main(String[] args) { TestThread1 t1 = new TestThread1("https://pic.netbian.com/uploads/allimg/200102/193708-15779650287a6a.jpg","女孩起床夜景.jpg"); TestThread1 t2 = new TestThread1("https://pic.netbian.com/uploads/allimg/210819/220400-1629381840d7b6.jpg","弓箭美女.jpg"); TestThread1 t3 = new TestThread1("https://pic.netbian.com/uploads/allimg/210616/235141-1623858701738e.jpg","樱花.jpg"); new Thread(t1).start(); new Thread(t2).start(); new Thread(t3).start(); } } //下载器 class WebDOwnLoder{ public void downloder(String url,String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO异常!downloder方法出现异常"); } } }
练习2:模拟龟兔赛跑
-
Thread.currentThread().getName().equals()
-
Thread.currentThread().getName()
-
Thread.sleep(10);
//模拟龟兔赛跑 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 falg = gameOver(i); if (falg){ break; } System.out.println(Thread.currentThread().getName()+"-->跑了:"+i+"步!"); } } //GameOver 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(); } }
静态代理模式
总结:
-
真实对象和代理对象都要实现同一个接口。
-
代理对象要代理真实角色。
//静态代理对象 public class StaricProxy { public static void main(String[] args) { 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("布置现场!"); } }
Lamde表达式
函数式接口:
-
任何接口,如果只包含唯一一个抽象方法,就是一个函数式接口。
-
函数式接口可以用Lamde表达式来创建。
public class TestLamde { //3.静态内部类 static class Like2 implements ILike{ @Override public void lamde() { System.out.println("i like lamde2 !"); } } public static void main(String[] args) { ILike like = new Like(); like.lamde(); like = new Like2(); like.lamde(); //4.局部内部类 class Like3 implements ILike{ @Override public void lamde() { System.out.println("i like lamde3 !"); } } like = new Like3(); like.lamde(); //5.匿名内部类 like = new ILike() { @Override public void lamde() { System.out.println("i like lamde4 !"); } }; //用lamde简化 like = () -> { System.out.println("i like lamde5 !"); }; like.lamde(); } } //1.定义一个函数式接口 interface ILike{ void lamde(); } //2.实现类 class Like implements ILike{ @Override public void lamde() { System.out.println("i like lamde !"); } }
线程状态
线程有五大状态:创建状态、就绪状态、阻塞状态、运行状态、死亡状态。
1.线程停止
-
1,建议线程正常停止 ——>利用次数,不建议死循环。
-
2,建议使用标志位 ——>设置一个标志位。
-
3,不要使用 stop() 或 destroy() 等过时的方法。
//线程停止 public class TestStop 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) { TestStop testStop = new TestStop(); new Thread(testStop).start(); for (int i = 0; i < 1000; i++) { if (i == 900){ //调用stop()停止线程 testStop.stop(); System.out.println("线程停止了"); } } } }
2.线程休眠
-
sleep( 时间 ) 指定当前线程阻塞毫秒数;
-
sleep存在异常;
-
sleep时间到达后线程进入就绪状态;
-
每个对象都有一把锁,sleep不会释放锁。
//模拟网络延时,放大问题的发生性 public class TestSleep implements Runnable{ //票数10张 private int ticketNums = 10; @Override public void run() { while (true){ if (ticketNums <= 0){ break; } //模拟延时 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"-->拿到了第 "+ ticketNums-- +" 张票!"); } } public static void main(String[] args) { TestSleep testSleep = new TestSleep(); new Thread(testSleep,"小明").start(); new Thread(testSleep,"小红").start(); new Thread(testSleep,"小花").start(); } }
//模拟倒计时、获取当前时间 import java.text.SimpleDateFormat; import java.util.Date; public class TestSleep2 { public static void tenDown() throws InterruptedException { int num = 10; while (true){ if (num<0){ break; } System.out.println(num--); Thread.sleep(1000); } } public static void main(String[] args) throws InterruptedException { // tenDown(); //打印系统当前时间 Date date = new Date(System.currentTimeMillis()); while (true){ Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(date)); //设置输出格式 date = new Date(System.currentTimeMillis()); //更新当前时间 } } }
3.线程礼让 ( Yield )
-
礼让线程,让当前正在执行的线程暂停,但不阻塞。
-
让线程从运转状态转为就绪状态。
-
让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()+"线程停止运行!"); }}
4.线程强制执行 ( Join )
-
Join合并线程,待此线程执行完毕后,再执行其他线程,其他线程阻塞。
//测试Join方法 public class TestJoin implements Runnable{ @Override public void run() { for (int i = 0; i < 500; i++) { System.out.println("线程开始运行! ------------------->" +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 < 500; i++) { if (i==200){ thread.join(); //插队 } System.out.println("main()方法里面的方法!"+i); } } }
5.观测线程状态
-
Thread.State.TERMINATED
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(100); state = thread.getState(); //更新线程状态 System.out.println(state); } }}
线程的优先级( priority )
-
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按优先级决定先执行哪个线程。
-
线程优先级用数字表示,范围从1~10。
-
线程优先级高的不一定先跑。
-
使用以下方式改变或获取优先级。
-
getPriority()
-
setPriority ( int xxx )
-
//设置线程优先级 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(); //最大优先级,MAX_PRIORITY=10 t4.setPriority(Thread.MAX_PRIORITY); 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()); } }
守护线程( 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 < 35600; i++) { System.out.println("活着!!"); } System.out.println("Goodbye! World"); } }
线程同步机制
-
锁机制( synchronized );
1.三大不安全案例
//不安全线程一:买票 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 ticketNumbers = 10; boolean flag = true; @Override public void run() { while (flag){ try { buy(); } catch (InterruptedException e) { e.printStackTrace(); } } } //买票 private void buy() throws InterruptedException { if (ticketNumbers<=0){ flag = false; return; } Thread.sleep(100); System.out.println(Thread.currentThread().getName()+"--拿到了第:"+ ticketNumbers-- +"张票!!"); } }
//不安全线程二:取钱 public class UnsafeBank { public static void main(String[] args) { // Drawing drawing = new Drawing(new Account("结婚基金",100),100); // // new Thread(drawing,"you").start(); // new Thread(drawing,"girlfriend").start(); Account account = new Account("结婚基金", 100); new Drawing(account,50,"you").start(); new Drawing(account,100,"girlfriend").start(); } } //账户 class Account{ String name; //账户名 int money; //余额 public Account(String name, int money) { this.name = name; this.money = money; } } //取钱 class Drawing extends Thread{ Account account; int drawingMoney; //取了多少钱 public Drawing(Account account,int drawingMoney,String name){ super(name); this.account = account; this.drawingMoney = drawingMoney; } @Override public void run() { try { drawingMoney(); } catch (InterruptedException e) { e.printStackTrace(); } } //取钱 public void drawingMoney() throws InterruptedException { System.out.println(Thread.currentThread().getName()+"-->"+"来取钱!"); if (account.money - drawingMoney < 0){ System.out.println(Thread.currentThread().getName()+"余额不足!"); return; } sleep(1000); account.money -= drawingMoney; System.out.println(this.getName()+"取走了:"+drawingMoney+"元!"+account.name+"余额:"+account.money); } }
import java.util.ArrayList; import java.util.List; //不安全线程三:泛型 public class UnfaseList { public static void main(String[] args) throws InterruptedException { List<String> list = new ArrayList<String>(); for (int i = 0; i < 1000; i++) { new Thread(()->{ list.add(Thread.currentThread().getName()); }).start(); } Thread.sleep(3000); //打印数组长度 System.out.println(list.size()); } }
2.同步方法及同步块
一、同步方法:
-
由于通过private关键字来保证数据对象只能被方法访问,所以只需针对方法提出一套机制,synchronized方法和synchronized块。
public synchronized method(int args){}
-
synchronized方法控制对 “ 对象 ” 的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用改方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,知道方法返回才释放锁。
-
缺点:影响效率。
二、同步块
-
synchronized ( Obj ) { }
-
Obj称之为同步监视器。Obj可以是任何对象,但是推荐使用共享资源作为同步监视器。
//同步块 public class UnsafeBank { public static void main(String[] args) { // Drawing drawing = new Drawing(new Account("结婚基金",100),100); // // new Thread(drawing,"you").start(); // new Thread(drawing,"girlfriend").start(); Account account = new Account("结婚基金", 100); new Drawing(account,50,"you").start(); new Drawing(account,100,"girlfriend").start(); } } //账户 class Account{ String name; //账户名 int money; //余额 public Account(String name, int money) { this.name = name; this.money = money; } } //取钱 class Drawing extends Thread{ Account account; int drawingMoney; //取了多少钱 public Drawing(Account account,int drawingMoney,String name){ super(name); this.account = account; this.drawingMoney = drawingMoney; } @Override public void run() { try { drawingMoney(); } catch (InterruptedException e) { e.printStackTrace(); } } //取钱 public void drawingMoney() throws InterruptedException { //锁的对象是变化的量 synchronized (account){ System.out.println(Thread.currentThread().getName()+"-->"+"来取钱!"); if (account.money - drawingMoney < 0){ System.out.println(Thread.currentThread().getName()+"余额不足!"); return; } sleep(1000); account.money -= drawingMoney; System.out.println(this.getName()+"取走了:"+drawingMoney+"元!"+account.name+"余额:"+account.money); } } }
三、扩充:JUC安全类型的集合 CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList; //测试JUC安全类型的集合 public class TestJUC { public static void main(String[] args) throws InterruptedException { CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<String>(); for (int i = 0; i < 1000; i++) { new Thread(()->{ copyOnWriteArrayList.add(Thread.currentThread().getName()); }).start(); } Thread.sleep(3000); System.out.println(copyOnWriteArrayList.size()); } }
3.死锁
-
多个线程各自占有一些共有的资源,并且等待其他线程占有的资源才能运行,而导致两个或多个线程都在等待对方释放资源,都形成停止执行的情况,某一个同步块同时拥有两个以上对象的锁,就会产生 死锁 问题。
//死锁 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 Millo{} class Makeup extends Thread{ //需要的资源,只有一份用static static Lipstick lipstick = new Lipstick();//口红 static Millor millor = new Millor();//镜子 int choice;//选择 String name;//人 public Makeup(int choice,String name){ this.choice = choice; this.name = name; } @Override public void run() { //化妆 try { makeup(); } catch (InterruptedException e) { e.printStackTrace(); } } public void makeup() throws InterruptedException { if (choice==0){ synchronized (lipstick){ System.out.println(this.name+":获得口红!"); Thread.sleep(1000); } synchronized (millor){ System.out.println(this.name+":获得镜子!"); } }else { synchronized (millor){ System.out.println(this.name+":获得镜子!"); Thread.sleep(2000); } synchronized (lipstick){ System.out.println(this.name+":获得口红!"); } } } }
4.Lock(锁)
-
显示定义同步锁;
-
Lock接口是控制多个线程对共享资源进行访问的工具;
-
ReentrantLock 类实现了Lock接口;
-
加锁:lock(); 解锁:unlock();
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(); } } } }
线程协作
1.生产者消费者问题
-
wait() 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁;
-
notigy() 唤醒一个处于等待的线程。
一、管程法
//测试生产者消费者模型,利用缓冲区:管程法 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 synContainer; public Productor(SynContainer synContainer){ this.synContainer = synContainer; } //生产 @Override public void run() { for (int i = 0; i < 100; i++) { synContainer.push(new Chichen(i)); System.out.println("生产了:"+i+"只鸡!"); } } } //消费者 class Consumer extends Thread{ SynContainer synContainer; public Consumer(SynContainer synContainer){ this.synContainer = synContainer; } //消费 @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println("消费了第:"+synContainer.pop().id+"只鸡!!"); } } } //产品 class Chichen{ int id;//编号 public Chichen(int id) { this.id = id; } } //缓冲区 class SynContainer{ //容器大小 Chichen[] chichens = new Chichen[10]; //容器计数器 int count =0; //生产者放入产品 public synchronized void push(Chichen chichen){ //如果容器满了,就需要等待消费者 if (count==chichens.length){ //通知消费者 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果没满就需要丢入产品 chichens[count] = chichen; count++; this.notifyAll(); } //消费者 public synchronized Chichen pop(){ //判断是否能消费 if (count==0){ //等待生产者生产 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //消费 count--; Chichen chichen = chichens[count]; //吃完了,通知生产者 this.notify(); return chichen; } }
二、信号灯法
//测试生产者消费者模型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++) { this.tv.watch(); } } } //观看 class TV{ //节目 String voice; boolean flag = true; //表演 public synchronized void play(String voice){ if (!flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.voice =voice; System.out.println("演员表演了:"+voice); this.notifyAll(); this.flag = !this.flag; } //观看 public synchronized void watch(){ if (flag){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("观看了:"+voice); this.notify(); this.flag = !this.flag; } }
线程池
-
优点:
-
提高响应速度;
-
降低资源消耗;
-
便于线程管理。
-
-
参数:
-
corePoolSize:核心池的大小;
-
maximumPoolSize:最大线程数;
-
keepALivetime:线程没有任务时最多保持多长时间后终止。
-
-
ExecutorService:真正的线程池接口,常见子类ThreadPoolExector。
-
void execute (Runnable command) : 执行任务/命令,没有返回值,一般用来执行Runnable。
-
void shutdown ():关闭连接池。
-
-
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池。
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()+i); } }