多线程
多线程
程序:指令和数据的有序集合,本身没有任何运行的含义,是一个静态的概念。
进程:程序的一次执行过程,是一个动态的概念,是系统资源分配的单位。
线程:一个进程可以包含多个线程,当然一个进程中至少有一个线程。线程是CPU调度和执行的单位。
线程的三种创建方式:Thread class、Runnable接口、Callable接口
Thread
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
public class StartThread1 extends Thread{
//线程入口点 重写run方法
public void run(){
//线程体
for(int i=0; i<20; i++){
System.out.println("我在听课.....")
}
}
public static void main(String[] args){
//创建线程对象
StartThread1 t=new StartThread1();
t.start();
}
}
//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread2(String url, String name){
this.url=url;
this.name=name;
}
//重写run方法 下载图片线程的执行体
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("url","name");
TestThread2 t2=new TestThread2("url","name");
TestThread2 t3=new TestThread2("url","name");
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
- 定义Runnable类实现Runnable接口
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
public class StartThread3 implements Runnable{
//线程入口点 重写run方法
public void run(){
//线程体
for(int i=0; i<20; i++){
System.out.println("我在听课.....")
}
}
public static void main(String[] args){
//创建线程对象
StartThread3 t=new StartThread3();
//创建代理类
Thread thread=new Thread(t);
//启动
t.start();
}
}
推荐使用:避免单继承局限性,方便同一个对象被多个线程使用
//多个线程同时操作同一个对象 (买火车票的例子)
//发现问题:多个线程操作同一资源的情况下,线程不安全,数据紊乱。
public class TestThread4 implements Runnable{
//票数
private int ticketNums=10;
//线程入口点 重写run方法
public void run(){
//线程体
while(true){
if(ticketNums<=0){
break;
}
//模拟延时
try{
Thread.sleep(200);
}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();
}
}
/* 案例:龟兔赛跑
1.首先来个塞道距离,然后要离终点越来越近。 2.判断比赛是否结束 3.打印出胜利者 4.龟兔赛跑开始
5.故事中是乌龟赢得,兔子需要睡觉,所以我们来模拟兔子睡觉。 6.终于,兔子赢得比赛
*/
public class Race implements Runnable{
//胜利者
private static String winner;
//线程入口点 重写run方法
public void run(){
//线程体
for(int i=0; i<=100; i++){
//模拟兔子休息
if(Thread.currentThread().getName().eauals("兔子") && i%10==0){
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag=gameOver(i);
//如果比赛结束了,就停止程序
if(flag){
break;
}
//Thread.currentThread().getName() 线程名
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();
}
}
静态代理
静态代理模式总结:
1. 真实对象和代理对象都要实现同一个接口。
2. 代理对象要代理真实角色。
3. 好处:代理对象可以做很多真实对象做不了的事情。真实对象专注做自己的事情。
public class StaticProxy{
public static void main(String[] args){
You you=new You();
WeddingCompany weddingCompany=new WeddingCompany(you);
weddingCompany.HappyMarry();
}
}
interface Marry{
public void HappyMarry();
}
//真实角色,你去结婚
public class You implements Marry{
public void HappyMarry(){
System.out.println("要结婚了,超开心!");
}
}
//代理角色,帮助你结婚
public class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Marry target){
this.target=target;
}
public void HappyMarry(){
before();
this.target.HappyMarry();
after();
}
private void before(){
System.out.println("结婚之前,布置现场");
}
private void after(){
System.out.println("结婚之后,收尾款");
}
}
Lamda表达式
/* 推导lamda表达式
*/
public class TestLamda{
//3.静态内部类
public static class Like2 implements ILike{
public void lamda(){
System.out.println("i like lamda2")
}
}
public static void main(String[] args){
ILike like=new Like();//用接口来创建一个类对象
like.lamda();
like=new Like2();
like.lamda();
//4.局部内部类
public class Like3 implements ILike{
public void lamda(){
System.out.println("i like lamda3");
}
}
like=new Like3();
like.lamda();
//5.匿名内部类,没有类的名称,必须借助接口或者父类
like=new ILike(){
public void lamda(){
System.out.println("i like lamda4");
}
};
//6.用lamda简化
like=()->{
System.out.println("i like lamda5");
};
like.lamda();
}
}
//1.定义一个函数式接口
interface ILike{
public void lamda();
}
//2.实现类
public class Like implements ILike{
public void lamda(){
System.out.println("i like lamda");
}
}
线程状态
- Thread t=new Thread() 线程对象一旦创建就进入到了新生状态。
- 当调用start()方法,线程立即进入就绪状态,但不意味着立即调度执行。
- 进入运行状态,线程才真正执行线程体的代码块。
- 当调用sleep,wait或同步锁定时,线程进入阻塞状态,就是代码不往下执行,阻塞时间解除后,重新进入就绪状态,等待cpu调度执行。
- 线程中断或者结束,一旦进入死亡状态,就不能再次启动。
/*停止线程:
建议利用次数来使线程正常停止,不建议死循环。
建议使用一个标志位进行终止变量,当flag=false,则终止线程运行。
不要使用stop或者destroy等过时或者JDK不建议使用的方法。
*/
public class TestStop implements Runnable{
//1.线程中定义线程体使用的标志
private boolean flag=true;
public void run(){
//2.线程体使用该标志
int i=0;
while(flag){
System.out.println("run....Thread"+i++);
}
}
//3.对外提供方法改变标识
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("线程该停止了");
}
}
}
}
/*线程休眠
sleep(时间)指定当前线程阻塞的毫秒数
sleep存在异常InterruptedException
sleep时间达到后线程进入就绪状态
sleep可以模拟网络延时,倒计时等
每一个对象都有一个锁,sleep不会释放锁
*/
//模拟倒计时
public class TestSleep{
public static void main(String[] args){
try{
tenDown();
}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 tenDown() throws InterruptedException{
int num=10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
线程礼让
- 让当前正在执行的线程暂停,但不阻塞。
- 将线程从运行状态转为就绪状态。
- 让cpu重新调度,礼让不一定成功,看cpu心情。
/*测试礼让线程
*/
public class TestYield{
oublic static void main(String[] args){
MyYield myYield=new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
public MyYield implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
join
- join合并线程,待线程执行完成后,再执行其它线程,其它线程阻塞。
/*测试join方法,想象成插队
*/
public class TestJoin implements Runnable{
public void run(){
for(int i=0; i<100; i++){
System.out.println("线程vip来了"+i);
}
}
public static void main(String[] args){
//启动我们的线程
TestJoin testJoin=new TestJoin();
new Thread(testJoin).start();
//主线程
for(int i=0; i<1000; i++){
if(i==200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
线程优先级
- 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看cpu的心情。
/*测试线程的优先级
*/
public class TestPriority{
oublic 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.getPriority(1);
t2.start();
t3.getPriority(4);
t3.start();
t4.getPriority(10);
t4.start();
t5.getPriority(8);
t5.start();
t6.getPriority(7);
t6.start();
}
}
public MyPriority implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName()+"线程开始执行"+"-->"+Thread.currentThread().getPriority());
}
}
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕
- 比如:后台记录操作日志,监控内存,垃圾回收等
/*测试守护线程
例子:
*/
public class TestDaemon{
God god=new God();
You you=new You();
Thread thread=new Thread(god);
thread.setDaemon(true);
thread.start();
Thread thread=new Thread(you);
thread.start();
}
//上帝
public class God implements Runnable{
public void run(){
while(true){
System.out.println("上帝保佑着你");
}
}
}
//你
public class You implements Runnable{
public void run(){
for(int i=0; i<36500; i++){
System.out.println("你一生都开心的活着");
}
System.out.println("======= goodbye world! =======");
}
}
线程同步
并发:同一个对象被多个线程同时操作。
//不安全的买票 线程不安全,有负数
public class UnsafeBuyTicket{
BuyTicket sation = new BuyTicket();
new Thread(station,"我").start();
new Thread(station,"你").start();
new Thread(station,"黄牛党").start();
}
public class BuyTicket implements Runnable{
//票
private int ticketNums=10;
boolean flag=true;//外部停止方式
public void run(){
//买票
while(flag){
try{
buy();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
private void buy(){
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
同步方法:
1. 我们通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种方法:synchronized方法和synchronized块。
2. synchronized方法控制对”对象“的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞。方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
//安全的买票 加了synchronized
public class UnsafeBuyTicket{
BuyTicket sation = new BuyTicket();
new Thread(station,"我").start();
new Thread(station,"你").start();
new Thread(station,"黄牛党").start();
}
public class BuyTicket implements Runnable{
//票
private int ticketNums=10;
boolean flag=true;//外部停止方式
public void run(){
//买票
while(flag){
try{
buy();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
private synchronized void buy() throw InterruptedException{
//判断是否有票
if(ticketNums<=0){
flag=false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
锁的对象就是变化的量,需要增删改的对象
死锁
多个线程互相抱着对方需要的资源,然后形成僵持。
public class DeadLock{
public static void main(String[] args){
Makeup g1=new Makeup(0,"灰姑娘");
Makeup g2=new Makeup(1,"白雪公主");
g1.start();
g2.start();
}
}
//口红
public class Lipstick{
}
//镜子
public class Mirror{
}
public class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
public static Lipstick lipstick = new Lipstick();
public static Mirror mirror = new Mirror();
public int choice;//选择
public String girlName;//使用化妆品的人
public Makeup(int choice, String girlName){
this.choice = choice;
this.girlName = girlName;
}
public void run(){
//化妆
try{
makeup();
}catch(InterruptedException e){
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup(){
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+"获得口红的锁");
}
}
}
}
}
//解决方法,不同时抱一把锁
public class DeadLock{
public static void main(String[] args){
Makeup g1=new Makeup(0,"灰姑娘");
Makeup g2=new Makeup(1,"白雪公主");
g1.start();
g2.start();
}
}
//口红
public class Lipstick{
}
//镜子
public class Mirror{
}
public class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
public static Lipstick lipstick = new Lipstick();
public static Mirror mirror = new Mirror();
public int choice;//选择
public String girlName;//使用化妆品的人
public Makeup(int choice, String girlName){
this.choice = choice;
this.girlName = girlName;
}
public void run(){
//化妆
try{
makeup();
}catch(InterruptedException e){
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup(){
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+"获得口红的锁");
}
}
}
}
产生死锁的四个必要条件
1. 互斥条件:一个资源每次只能被一个进程使用。
2. 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
3. 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺。
4. 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
//测试lock锁
public class TestLock{
public static void main(String[] args){
Testlock testlock = new Testlock();
new Thread(testlock).start();
new Thread(testlock).start();
new Thread(testlock).start();
}
}
public class Testlock implements Runnable{
int ticketNums=10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
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是不够的。
synchronized可阻止并发更新同一个共享资源,实现了同步。
synchronized不能用来实现不同线程之间的消息传递(通信)。
//测试:生产者消费者模型-->利用缓冲区解决:管理法
//生产者,消费者,产品,缓冲区
public class TestPC{
public static void main(String[] args){
new Producter(container).start();
new Consumer(container).start();
}
}
//生产者
public class Producter extends Thread{
Syncontainer container;
public Producter(Syncontainer container){
this.container = container;
}
//生产
public void run(){
for(int i=0; i<100; i++){
container.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
public class Consumer extends Thread{
Syncontainer container;
public Consumer(Syncontainer container){
this.container = container;
}
//消费
public void run(){
for(int i=0; i<100; i++){
System.out.println("消费了"+container.pop().id+"只鸡");
}
}
}
//产品
public class Chicken{
int id;//产品编号
public Chicken(int id){
this.id = id;
}
}
//缓冲区
public 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:信号灯法,标志位解决
public class TestPc2{
public static void main(String[] args){
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//生产者-->演员
public class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv = tv;
}
public void run(){
for(int i=0; i<20; i++){
if(i%2==0){
this.tv.play("快乐大本营播放中");
}else{
this.tv.play("抖音:记录美好生活");
}
}
}
}
//消费者-->观众
public class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv = tv;
}
public void run(){
for(int i=0; i<20; i++){
tv.watcher();
}
}
}
//产品-->节目
public class TV{
//演员表演,观众等待 true
//观众观看,演员等待 false
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;
}
}
线程池
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
void shutdown():关闭线程池
Excutors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池
//测试线程池
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();
}
}
public class MyThread implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
浙公网安备 33010602011771号