//方式一:继承Thread类,重写run()方法 public class demo01 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线程 主线程 //创建线程对象 demo01 demo01 = new demo01(); //调用start()方法开启线程:交替执行 多条路径 demo01.start(); //调用run()方法开启线程:顺序执行 一条路径 // demo01.run(); for (int i = 0; i < 20; i++) { System.out.println("学习多线程-----"+i); } } }
运行后结果
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法 public class demo02 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接口的实现类对象 demo02 demo02 = new demo02(); //创建线程对象,通过线程对象来开启我们的线程代理 Thread thread = new Thread(demo02); thread.start(); // new Thread(demo02).start(); for (int i = 0; i < 20; i++) { System.out.println("学习多线程-----"+i); } } }
小结:
- 继承Thread类
1.子类继承Thread类具备多线程能力
2.启动线程:子类对象.start()
3.不建议使用:避免OOP单继承局限性- 实现Runnable接口
1.实现接口Runnable具备多线程能力
2.启动线程:传入目标对象+Thread对象.start()
3.推荐使用:避免单继承的局限性,灵活方便,方便同一个对象被多个线程使用
//多个线程同时操作同一个对象 //案例:买火车票 public class Demo03 implements Runnable { //票数 private int ticketNums = 10; @Override public void run() { while (true){ if (ticketNums<=0){ break; } System.out.println(Thread.currentThread().getName()+"--->拿到了第"+ticketNums--+"票"); } } public static void main(String[] args) { Demo03 demo03 = new Demo03(); new Thread(demo03,"小明").start(); new Thread(demo03,"黄牛").start(); new Thread(demo03,"小红").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(5); } catch (InterruptedException e) { e.printStackTrace(); } } //判断比赛是否结束 boolean flag = gameOver(i); if (flag){ break; } System.out.println(Thread.currentThread().getName()+"跑了"+i+"步"); } } //判断是否完成比赛 public 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 StaticProxy { public static void main(String[] args) { 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; } private void before(){ System.out.println("结婚之前"); } private void after(){ System.out.println("结婚之后"); } @Override public void HappyMarry() { before(); this.target.HappyMarry(); after(); } }
小结:
1.真实对象和代理对象都要实现同一个接口
2.代理对象要代理真实对象
3.代理对象可以做很多真实对象做不了的事情
4.真实对象专注自己的事情
为什么要使用lambda表达式
1.避免匿名内部类定义过多
2.可以让你的代码看起来更简洁
3.去掉了一堆没有意义的代码,只留下核心的逻辑
理解Functional Interface(函数式接口)是学习java8 lambda表达式的关键所在
函数式接口的定义:
1.任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口
2.对于函数式接口,我们可以通过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 iLike = new Like(); iLike.lambda(); iLike = new Like2(); iLike.lambda(); //4.局部内部类 class Like3 implements ILike{ @Override public void lambda() { System.out.println("i like lambda3"); } } iLike = new Like3(); iLike.lambda(); //5.匿名内部类 iLike = new ILike() { @Override public void lambda() { System.out.println("i like lambda4"); } }; iLike.lambda(); //6.用lambda简化 iLike = ()->{ System.out.println("i like lambda5"); }; iLike.lambda(); } } //1.定义一个函数式接口 interface ILike{ void lambda(); } //2.实现类 class Like implements ILike{ @Override public void lambda() { System.out.println("i like lambda"); } }
//测试停止线程 //1.建议线程正常停止:利用次数,不建议死循环 //2.建议使用标志位 public class Stop implements Runnable{ //设置标志位 private boolean flag = true; @Override public void run() { int i = 0; while (flag){ System.out.println("run----"+i++); } } //设置公开的方法停止线程 public void stop(){ this.flag = false; } public static void main(String[] args) { Stop stop = new Stop(); new Thread(stop).start(); for (int i = 0;i<100;i++){ System.out.println("main"+i); if(i==90){ stop.stop(); System.out.println("线程停止"); } } } }
//模拟倒计时 public class Sleep2 { public static void main(String[] args) { // try { // testDown(); // } catch (InterruptedException e) { // e.printStackTrace(); // } //打印当前系统时间 Date startTime = new Date(System.currentTimeMillis()); while (true) { try { Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); //更新当前时间 startTime = new Date(System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } //模拟倒计时 public static void testDown() throws InterruptedException { int num = 10; while (true){ Thread.sleep(1000); System.out.println(num--); if (num<=0){ break; } } } }
//测试礼让,礼让不一定成功 public class Yield { 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()+"线程停止执行"); } }
public class State { 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); //观测启动后 thread.start(); state = thread.getState(); System.out.println(state); while (state != Thread.State.TERMINATED){//只要线程不终止,就是输出状态 Thread.sleep(100); state = thread.getState(); System.out.println(state); } } }
getPriority().setPriority(int xxx)
public class Priority{ 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); //先设置优先级在启动 t1.start(); t2.setPriority(1); t2.start(); t3.setPriority(4); t3.start(); t4.setPriority(Thread.MAX_PRIORITY); t4.start(); // t5.setPriority(-1); // t5.start(); } } class MyPriority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority()); } }
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度(性能倒置)
//守护线程 public class Daemon { public static void main(String[] args) { God god = new God(); You1 you1 = new You1(); Thread thread = new Thread(god); thread.setDaemon(true);//默认是false表示用户线程,正常的线程都是用户线程 thread.start();//上帝守护线程 new Thread(you1).start();//你 } } //上帝 class God implements Runnable{ @Override public void run() { while (true){ System.out.println("上帝保护你"); } } } //你 class You1 implements Runnable{ @Override public void run() { for (int i = 0; i < 36500; i++) { System.out.println("你开心的活着"); } System.out.println("你驾鹤西去----"); } }
多个线程操作同一个资源
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突的问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可,存在以下问题
//不安全的买票 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) { e.printStackTrace(); } } } private void buy() throws InterruptedException { //判断是否有票 if (ticketNums<=0){ flag = false; return; } Thread.sleep(100); //买票 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 girlfriend = new Drawing(account,100,"女朋友"); you.start(); girlfriend.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; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //卡内余额 = 余额 - 你取的钱 account.money = account.money - drawingMoney; //你手里的钱 nowMoney = nowMoney + drawingMoney; System.out.println(account.name+"余额为:"+account.money); System.out.println(this.getName()+"手里的钱"+nowMoney); } }
发现运行结果与预期的不一样,导致此原因就是线程不同步
//线程不安全的集合 public class UnsafeList { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for (int i = 0; i < 100; i++) { new Thread(() ->{ list.add(Thread.currentThread().getName()); }).start(); } System.out.println(list.size()); } }
对于上述中的不安全案例一中,对目标方法加上synchronized关键字即可变为同步方法
解决不安全案例中的取钱问题
synchronized同步代码块
@Override public void run() { synchronized(account){ //判断有没有钱 if (account.money-drawingMoney<0){ System.out.println(Thread.currentThread().getName()+"钱不够"); return; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //卡内余额 = 余额 - 你取的钱 account.money = account.money - drawingMoney; //你手里的钱 nowMoney = nowMoney + drawingMoney; System.out.println(account.name+"余额为:"+account.money); System.out.println(this.getName()+"手里的钱"+nowMoney); } }
//死锁,多线程互相抱着对方需要的资源,然后形成僵持 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); // //1秒钟后获得镜子的锁 // synchronized (mirror){ // System.out.println(this.girlName+"获得镜子的锁"); // // } } //1秒钟后获得镜子的锁 synchronized (mirror){ System.out.println(this.girlName+"获得镜子的锁"); } }else { synchronized (mirror){//获得口红的锁 System.out.println(this.girlName+"获得镜子的锁"); Thread.sleep(2000); // //2秒钟后获得口红的锁 // synchronized (lipstick){ // System.out.println(this.girlName+"获得口红的锁"); // // } } //2秒钟后获得口红的锁 synchronized (lipstick){ System.out.println(this.girlName+"获得口红的锁"); } } } }
//测试锁 public class Lock { public static void main(String[] args) { Lock2 lock2 = new Lock2(); new Thread(lock2).start(); new Thread(lock2).start(); new Thread(lock2).start(); } } class Lock2 implements Runnable{ int ticketNums = 10; //定义lock锁 //ReentrantLock:可重入锁 private 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();//解锁 } } } }
synchronized与Lock的对比
- Lock是显示锁(手动开启和关闭锁,别忘记关闭锁)synchronized是隐式锁,出了作用域自动释放
- Lock只有代码块锁,synchronized有代码块锁和方法锁
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类)
- 优先使用顺序:
Lock > 同步代码块(已经进入了方法体,分配了相应的资源)> 同步方法(在方法体之外)
并发协作模型“生产者/消费者模式”—>管程法
//管程法 public class Pc { 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; } }
并发协作模型“生产者/消费者模式”—>信号灯法
//线程池 public class Pool { public static void main(String[] args) { //1.创建服务,线程池 ExecutorService service = Executors.newFixedThreadPool(10); service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); //关闭连接 service.shutdown(); } } class MyThread implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()); } }
看完此篇,相信你对线程已经入门了吧!!