线程实现【重点】
线程名字
new Thread (testThread5,"销售A" ).start(); Thread.currentThread().getName()
Thread
public class TestThread1 extends Thread { @Override public void run () { for (int i = 0 ; i < 200 ; i++) { System.out.println("我在看代码---" + i); } } public static void main (String[] args) { TestThread1 testThread1=new TestThread1 (); testThread1.start(); for (int i = 0 ; i < 200 ; i++) { System.out.println("我在学习多线程--" ); } } }
注意
继承Thread 类,重写run()方法,调用start 开启线程
线程开启不一定立即执行,由cpu调度执行
java单继承,继承Thread无法继承其他类
public class TestThread2 extends Thread { private String url; private String name; public TestThread2 (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) { TestThread2 t1 = new TestThread2 ("https://chen-131.png" ,"1.png" ); TestThread2 t2 = new TestThread2 ("https://chen-131.jpg" ,"2.jpg" ); TestThread2 t3 = new TestThread2 ("https://chen-131.png" ,"3.png" ); 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方法出现问题" ); } } }
下载 – 导包 – commons-io
Runnable【*】
实现 Runnable 接口
实现 run() 方法
创建 Thread 对象 来开启 start() 线程
public class TestThread3 implements Runnable { @Override public void run () { for (int i = 0 ; i < 200 ; i++) { System.out.println("我在看代码---" + i); } } public static void main (String[] args) { TestThread3 testThread3 = new TestThread3 (); new Thread (testThread3).start(); for (int i = 0 ; i < 1000 ; i++) { System.out.println("我在学习多线程--" + i); } } }
new Thread (t1).start(); new Thread (t2).start(); new Thread (t3).start();
public class Race implements Runnable { private static String winner; @Override public void run () { for (int i = 1 ; i <= 100 ; i++) { if (Thread.currentThread().getName().equals("兔子" )&&i%10 ==0 ){ try { Thread.sleep(2 ); } 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 ; }else { 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接口
callable的好处
public class TestCallabel implements Callable { private String url; private String name; public TestCallabel (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 { TestCallabel t1 = new TestCallabel ("https://chen-1.png" ,"1.png" ); TestCallabel t2 = new TestCallabel ("https://chen-1.jpg" ,"2.jpg" ); TestCallabel t3 = new TestCallabel ("https://chen-1.png" ,"3.png" ); ExecutorService service = Executors.newFixedThreadPool(3 ); Future<Boolean> r1 = service.submit(t1); Future<Boolean> r2 = service.submit(t2); Future<Boolean> r3 = service.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); service.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方法出现问题" ); } } }
Lambda表达式
public class TestLambdal { public static void main (String[] args) { ILike iLike = new Like (); iLike.lambda(); } } interface ILike { void lambda () ; } class Like implements ILike { @Override public void lambda () { System.out.println("I Like Lambda" ); } }
public class TestLambdal { public static void main (String[] args) { ILike iLike = () ->{ System.out.println("I Like Lambda5" ); }; iLike.lambda(); } } 定义一个函数式接口 interface ILike { void lambda () ; }
public class TestLambda2 { public static void main (String[] args) { CP cpe=null ; cpe=(int a)->{ System.out.println("lambda : cpe-->" + a); }; cpe = (a)->{ System.out.println("lambda : cpe-->" + a); }; cpe = a -> { System.out.println("lambda : cpe-->" + a); }; cpe = a-> System.out.println("lambda : cpe-->" + a); } } interface CP { void cpe (int a) ; }
总结:
线程状态
观察线程状态 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); thread.start(); state = thread.getState(); System.out.println(state); while (state != Thread.State.TERMINATED) { Thread.sleep(100 ); state = thread.getState(); System.out.println(state); } } }
线程停止 –stop
1.建议线程正常停止 —–> 利用次数,不建议死循环
2.建议使用标志位 –> 设置一个标志位
3.不要使用 stop 或者 destroy 等过时或者JDK不建议使用的方法
public class TestTop 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) { TestTop testTop = new TestTop (); new Thread (testTop).start(); for (int i = 0 ; i < 1000 ; i++) { System.out.println("main " +i); if (i==900 ){ testTop.stop(); System.out.println("该线程停止了" ); } } } }
线程休眠–sleep
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(); } }
线程礼让–yield
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
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
插队
public class TestJoin implements Runnable { @Override public void run () { try { Thread.sleep(10000 ); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 0 ; i < 100 ; i++) { System.out.println("线程vip来了" +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("man " +i); } } }
线程优先级–priority
public class TestPriority { public static void main (String[] args) { System.out.println(Thread.currentThread().getName()+"-->" +Thread.currentThread().getPriority()); MyPrority myPrority = new MyPrority (); Thread t1 = new Thread (myPrority); Thread t2 = new Thread (myPrority); Thread t3 = new Thread (myPrority); Thread t4 = new Thread (myPrority); Thread t5 = new Thread (myPrority); Thread t6 = new Thread (myPrority); t1.start(); t2.setPriority(2 ); t2.start(); t3.setPriority(6 ); t3.start(); t4.setPriority(Thread.MAX_PRIORITY); t4.start(); t5.setPriority(Thread.MIN_PRIORITY); t5.start(); t6.setPriority(1 ); t6.start(); } } class MyPrority implements Runnable { @Override public void run () { System.out.println(Thread.currentThread().getName()+"-->" +Thread.currentThread().getPriority()); } }
守护线程–daemon
即 守护线程 会**陪伴 **被守护的线程 执行完毕
//true则设置为守护线程
//默认是false表示是用户线程,正常的线程都是用户线程
thread.setDaemon(true);
```java 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("==================bye===================="); } }
线程同步【重点】 并发
安全集合CopyOnWriteArrayList
不需要锁,各线程排队进行
public class TestJUC { public static void main (String[] args) throws InterruptedException { CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList (); for (int i = 0 ; i < 1000 ; i++) { new Thread (()->{ list.add(Thread.currentThread().getName()); }).start(); } Thread.sleep(100 ); System.out.println(list.size()); } }
锁机制 – synchronized
synchronized方法
锁 类本身 private synchronized void buy(){ }
public class UnsafeBuyTicket { public static void main (String[] args) { BuyTicket station = new BuyTicket (); new Thread (station,"A员工" ).start(); new Thread (station,"B员工" ).start(); new Thread (station,"C员工" ).start(); } } class BuyTicket implements Runnable { private int ticketNums = 10 ; boolean flag = true ; @Override public void run () { while (flag){ buy(); try { Thread.sleep(100 ); } catch (InterruptedException e) { e.printStackTrace(); } } } private synchronized void buy () { if (ticketNums<=0 ){ flag=false ; return ; } System.out.println(Thread.currentThread().getName()+"拿到" +ticketNums--); } }
synchronized块
可以锁任意对象 synchronized (account){ }
锁的对象:变化的量,需要增删改的量
package com.synchronizedc;public class UnsafeBank { public static void main (String[] args) { Account account = new Account (1000 ,"结婚基金" ); Drawing you = new Drawing (account,50 ,"你" ); Drawing girlFirend = new Drawing (account,100 ,"girlFirend" ); girlFirend.start(); you.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 () { 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 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 ); } 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(锁)
定义:private final ReentrantLock lock = new ReentrantLock();
在 try 中上锁,finally 中解锁
显式锁,手动开启和关闭
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 ; 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(); } } } }
总结:
线程通信问题 生产者消费者模式
管程法
public class TestPC { public static void main (String[] args) { SyncContainer container=new SyncContainer (); new Productor (container).start(); new Consumer (container).start(); } } class Productor extends Thread { SyncContainer container; public Productor (SyncContainer 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 { SyncContainer container; public Consumer (SyncContainer 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 SyncContainer { 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 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) { e.printStackTrace(); } } 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) { e.printStackTrace(); } } System.out.println("观看了:" +voice); this .notifyAll(); this .flag=!this .flag; } }
线程池
public class TestPool { public static void main (String[] args) { ExecutorService service = Executors.newFixedThreadPool(10 ); service.execute(new MyThread ()); service.execute(new MyThread ()); service.execute(new MyThread ()); service.execute(new MyThread ()); service.execute(new MyThread ()); service.shutdownNow(); } } class MyThread implements Runnable { @Override public void run () { System.out.println(Thread.currentThread().getName()); } }