线程知识点Demo

本文深入探讨了多线程的概念,包括进程与线程的区别、线程创建的方式(继承Thread类和实现Runnable接口)、网络图片下载示例、线程状态与控制、优先级、守护线程、同步机制(锁和死锁解决)、线程池、并发编程实践以及线程安全问题。
摘要由CSDN通过智能技术生成

多线程

进程:执行程序的一次执行过程,进程里面包含若干个线程。

线程是CPU调度和执行的单位。main函数(住线程)

线程创建

一个是将一个类声明为Thread的子类。 这个子类应该重写run类的方法Thread 。 然后可以分配并启动子类的实例。

package ThreadPackage;
public class ThreadDemo1 extends Thread{
    @Override
    public void run()
    {
        for (int i = 0;i<20;i++)
        {
            System.out.println("输出i--------->"+i);
        }
    }
    public static void main(String[] args) {
        //main线程 主线程
        //创建一个线程对象
        ThreadDemo1 threadDemo1 = new ThreadDemo1();
        threadDemo1.start();
        for (int i = 0;i<20;i++)
        {
            System.out.println("输出i--------->"+i);
        }
    }
}

实例网络图片下载

package ThreadPackage;
import org.apache.commons.io.FileUtils;//需要导入包:commons.io  
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class ThreadDemo2 extends Thread{
    private String url;
    private String name;
    public ThreadDemo2(String name, String url) {
        this.name = name;
        this.url = url;
    }

    @Override
    public void run()
    {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载文件名为:" + name);
    }
    
    public static void main(String[] args) {
        ThreadDemo2 threadDemo2 = new ThreadDemo2("test1.jpg","https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic3.zhimg.com%2F50%2Fv2-8c9651124a6643b29371da3b4b34a73f_hd.jpg&refer=http%3A%2F%2Fpic3.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1641568943&t=706e6e20d943b75a7302435be7e0c8e6");
        threadDemo2.start();
    }
}
//下载器
class WebDownloader{
    //下载方法
    public void downloader(String url,String name) {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Runnable接口创建线程

package ThreadPackage;

public class ThreadDemo3 implements Runnable {

    @Override
    public void run() {
        for (int i = 0;i<200;i++)
        {
            System.out.println("输出"+i);
        }
    }

    public static void main(String[] args) {
//        PrimeRun p = new PrimeRun(143);
//        new Thread(p).start();
//        创建Runnable接口实现类的对象
        ThreadDemo3 threadDemo3 = new ThreadDemo3();
//        创建线程对象,通过线程对象来开启线程,代理 等价于 ===> new Thread(threadDemo3).start();
//        Thread thread = new Thread(threadDemo3);
//        thread.start();
        new Thread(threadDemo3).start();
    }
}

龟兔赛跑实例

package ThreadPackage;
//模拟龟兔赛跑
public class ThreadDemo6 implements Runnable{
    //胜利者
    private static String winner;
    @Override
    public void run() {
        //判断比赛是否结束
        for (int i = 0;i<=100;i++)
        {
            boolean flag = gameover(i);
//            如果比赛结束了就停止程序
            if (flag){
                break;
            }
            if (Thread.currentThread().getName().equals("兔子") && (i%10)==0)
            {
                try {
                    Thread.sleep(10);
                }catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            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) {
        ThreadDemo6 threadDemo6 = new ThreadDemo6();
        new Thread(threadDemo6,"兔子").start();
        new Thread(threadDemo6,"乌龟").start();
    }
}

Callable接口创建线程(了解即可)

静态代理

package Proxystatic;
public interface Movie {
    void paly();
}

package Proxystatic;
//被代理类
public class RealMovie implements Movie{
    @Override
    public void paly() {
        System.out.println("电影准备播放了");
    }
}

package Proxystatic;
//代理类
public class proxyMovie implements Movie{
    RealMovie realMovie;
    proxyMovie(RealMovie realMovie){
        this.realMovie = realMovie;
    }
    @Override
    public void paly() {
        guanggao(true);
        realMovie.paly();
        guanggao(false);
    }
    public void guanggao(boolean isStart){
         if ( isStart ) {
                 System.out.println("电影马上开始了,爆米花、可乐、口香糖9.8折,快来买啊!");
             } else {
                 System.out.println("电影马上结束了,爆米花、可乐、口香糖9.8折,买回家吃吧!");
             }
     }
}

package Proxystatic;
public class Proxytest {
    public static void main(String[] args) {
     //   proxyMovie p = new proxyMovie(new RealMovie());
     //   p.paly();
     //	等价于==  new proxyMovie(new RealMovie()).paly();   
     //线程也是使用代理模式设计的, lamda表达式
     //new Thread(()-->System.out.println("我是被代理的对象");).Start();
     new proxyMovie(new RealMovie()).paly();
    }
}

Lamda表达式(函数式编程)

函数式接口定义:任何接口如果只包含唯一一个抽象方法,那么他就是一个函数式接口。

package Lamda;

/*
推到Lamda表达式
 */
public class LamdaDemo1 {

    //静态内部类
    static class Demo1impl2 implements Demo1interface{
        @Override
        public void lamba() {
            System.out.println("实现接口Demo1interface");
        }
    }
    public static void main(String[] args) {
        Demo1interface demo1impl = new Demo1impl();
        demo1impl.lamba();

        Demo1interface demo1impl2 = new Demo1impl2();
        demo1impl2.lamba();

        //局部内部类
        class Demo1impl3 implements Demo1interface{

            @Override
            public void lamba() {
                System.out.println("实现接口Demo1interface");
            }
        }

        Demo1interface demo1impl3 = new Demo1impl3();
        demo1impl3.lamba();

        //匿名内部类
        Demo1interface demo1impl4 = new Demo1interface() {
            @Override
            public void lamba() {
                System.out.println("匿名内部类实现了接口");
            }
        };
        demo1impl4.lamba();

        //用lamda简化  
        Demo1interface demo1impl5 = ()->{
            System.out.println("lamda实现了接口");
        };
        demo1impl5.lamba();
        
    }
}

interface Demo1interface {
    void lamba();
}
 class Demo1impl implements Demo1interface{
    @Override
    public void lamba() {
        System.out.println("实现接口Demo1interface");
    }
}

练习lamda表达式有参数

package Lamda;
import java.sql.SQLOutput;
public class LamdaDemo2 {
    public static void main(String[] args) {
//        Ilove b =(int a)-> {
//            System.out.println("*******************输出**************"+ a);
//        };
//        b.love(6);
//        Ilove b =(a)-> {
//            System.out.println("*******************输出**************"+ a);
//        };
//        b.love(6);

//        Ilove b =a-> {
//            System.out.println("*******************输出**************"+ a);
//        };
//        b.love(6);

        //简化花括号,前提是代码只有一行
        Ilove b =a-> System.out.println("*******************输出**************"+ a);
        b.love(6);
    };
    }
interface Ilove{
    void love(int i);
}
//class love implements Ilove{
//    @Override
//    public void love(int i) {
//        System.out.println("*******************输出**************"+ i);
//    }
//}

线程的状态

new, 就绪(start()), 运行状态, 阻塞状态(sleep,wait),Dead.

线程停止:

1.利用次数不建议死循环

2.标志位

3.不建议使用stop和destory方法

//停止案例
package ThreadPackage;
public class ThreadDemo7 implements Runnable{
//    1.设置一个标志位
    private boolean flag = true;
    @Override
    public void run() {
        while (flag)
        {
            System.out.println("线程开始跑了");
        }
        System.out.println("线程停止了----->"+ Thread.currentThread().getName());
    }
    public void stoprun(){
        this.flag = false;
    }
    public static void main(String[] args) {
        ThreadDemo7 threadDemo7 = new ThreadDemo7();
        new Thread(threadDemo7,"ITQIGO").start();
        for (int i = 0 ;i<=1000; i++)
        {
            System.out.println("输出i------------------>"+i);
            if (i==900)
            {
                System.out.println("i=900 开始调用stoptun 方法");
                threadDemo7.stoprun();
            }
        }
    }
}

休眠案例:模拟倒计时

package ThreadPackage;
//备注:每个对象都有一把锁,sleep不会释放锁 ------>不懂,慢慢理解.
//模拟倒计时
public class ThreedSleep2 implements Runnable{

    public static void main(String[] args) {
        ThreedSleep2 threedSleep2 = new ThreedSleep2();
        new Thread(threedSleep2).start();
    }
    @Override
    public void run() {
        int num = 10;
        while (true)
        {
            try {
                Thread.sleep(1000);
                System.out.println("倒计时:--------->" + num--);
                if (num < 0)
                {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

礼让案例:礼让不一定成功。

package ThreadPackage;
public class ThreadYield {
    public static void main(String[] args) {
        MyYeild myYeild = new MyYeild();
        new Thread(myYeild,"a").start();
        new Thread(myYeild,"b").start();
    }
}
class MyYeild implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield(); //礼让
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}
/* 礼让成功
a线程开始执行
b线程开始执行
b线程停止执行
a线程停止执行
*/
/*礼让失败
a线程开始执行
a线程停止执行
b线程开始执行
b线程停止执行
*/

JOIN用法

join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞。

package ThreadPackage;

public class ThreadJoin implements Runnable{
    @Override
    public void run() {
        for (int i =0;i<10000; i++)
        {
            System.out.println("线程vip来了------>" + i );
        }
    }
    public static void main(String[] args) throws InterruptedException {
        //ThreadJoin线程
        ThreadJoin threadJoin = new ThreadJoin();
        Thread thread = new Thread(threadJoin);
        thread.start();
        // new Thread(threadJoin).start();
        //main线程
        for (int i = 0 ; i<100;i++)
        {
            if (i==50)
            {
                thread.join();//插队
            }
            System.out.println("main......" + i);
        }

    }
}

观察线程的状态

package ThreadPackage;
public class ThreadState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i=0;i<6;i++)
            {
                try {
                    Thread.sleep(1000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("/");
        }) ;
		//         Thread.State 枚举
        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);
        }
        //死亡之后的线程不能再重新启动
        thread.start();
    }
}

线程的优先级

package ThreadPackage;
public class ThreadPriority {
    public static void main(String[] args) {
        Mythread mythread = new Mythread();
        Thread thread1 =  new Thread(mythread);
        Thread thread2 =  new Thread(mythread);
        Thread thread3 =  new Thread(mythread);
        Thread thread4 =  new Thread(mythread);
        Thread thread5 =  new Thread(mythread);
        Thread thread6 =  new Thread(mythread);
        
        //先设置优先级 再启动
        thread1.setPriority(1);
        thread1.start();
        thread2.setPriority(2);
        thread2.start();
        thread3.setPriority(4);
        thread3.start();
        thread4.setPriority(6);
        thread4.start();
        thread5.setPriority(7);
        thread5.start();
        thread6.setPriority(10);
        thread6.start();
    }

}

class Mythread implements  Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "输出优先级-------------------->" + Thread.currentThread().getPriority());
    }
}
/*
输出结果:
Thread-0输出优先级-------------------->1
Thread-5输出优先级-------------------->10
Thread-4输出优先级-------------------->7
Thread-3输出优先级-------------------->6
Thread-2输出优先级-------------------->4
Thread-1输出优先级-------------------->2
结论:优先级高的不一定先执行
*/

守护(daemon)线程

package ThreadPackage;
public class ThreadDeamon {
    public static void main(String[] args) {
        God god = new God();
        user user = new user();

        Thread thread = new Thread(god);
        thread.setDaemon(true);//设置守护线程
        thread.start();

        Thread thread1 = new Thread(user);
        thread1.start();
    }
}
class God implements  Runnable{
    @Override
    public void run() {
        while (true)
        {
            System.out.println("我是守护线程");
        }
    }
}
class user implements  Runnable{
    @Override
    public void run() {
        for (int i=0;i<100;i++)
        {
            System.out.println("我是用户线程-------->" + i);
        }
    }
}
/*
1. 虚拟机必须确保用户线程执行完毕
2. 虚拟机不用等待守护线程执行完毕
3. 如:后台记录操作日志,垃圾回收等待,监控内存。
*/

线程同步

1.队列和锁(synchronized)

使用实例:synchronized(obj){} obj 需要增删改的对象。

线程不安全实例

死锁案例
1.加入synchronized 解决死锁问题
package ThreadPackage;
import java.util.ArrayList;
import java.util.List;

//线程不安全集合 数组问题
public class Unsafeshuzu {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();

        for (int i=0;i<1000;i++)
        {
           /* new Thread(() ->{
               list.add(Thread.currentThread().getName()).start;
            });
            加入synchronized
            */
            new Thread(() ->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        Thread.sleep(3000); //问题 去除sleep后还是没有1000
        System.out.println(list.size());
    }
}
package ThreadPackage;
//买票问题
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        Thread thread = new Thread(buyTicket);
        Thread thread1 = new Thread(buyTicket);
        Thread thread2 = new Thread(buyTicket);

        thread.start();
        thread1.start();
        thread2.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 { 加入锁后
	private synchronized void buy() throws InterruptedException {        
        if (ticketNums <= 0)
        {
            flag = false;
            return;
        }
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}

package ThreadPackage;
//取钱问题
public class UnsafeBlank {
    public static void main(String[] args) {
        Account account = new Account(100,"结婚积金");
        Drawing you = new Drawing(account,50 ,"你");
        Drawing grilfriend = new Drawing(account,100 ,"grilfriend");
        
        you.start();
        grilfriend.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
       synchronized(account){
            if (account.money - drawingMoney < 0 )
            {
                System.out.println(Thread.currentThread().getName() + "钱不够取不了");
                return;
            }
            try {
                //Sleep 放大问题发生性
                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);   
       }
    }
}
package ThreadPackage;
//死锁:多个线程互相抱着对方需要的资源,然后形成死锁
public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup(0,"灰姑凉");
        Makeup makeup1 = new Makeup(1,"白雪公主");
        makeup.start();
        makeup1.start();
    }
}

//口红
class Lipstick{

}

//镜子
class Mirror{

}
class Makeup extends  Thread{
    //需要的资源只有一份,有static来保证只有一份
    static Lipstick lipstick = new Lipstick();
    static  Mirror mirror = new Mirror();

    int chioce;//选择
    String girlName; //使用化妆品的人

    Makeup(int chioce,String girlName)
    {
        this.chioce = chioce;
        this.girlName = girlName;
    }
    @Override
    public  void run()
    {
      //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };
    
    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (chioce ==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 + "获得口红的锁");
                }
            }
        }
    }
}
------------------------------------------------------------------------------------------------------
解决方法:
package ThreadPackage;
//死锁:多个线程互相抱着对方需要的资源,然后形成死锁
public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup(0,"灰姑凉");
        Makeup makeup1 = new Makeup(1,"白雪公主");
        makeup.start();
        makeup1.start();
    }
}

//口红
class Lipstick{

}

//镜子
class Mirror{

}
class Makeup extends  Thread{
    //需要的资源只有一份,有static来保证只有一份
    static Lipstick lipstick = new Lipstick();
    static  Mirror mirror = new Mirror();

    int chioce;//选择
    String girlName; //使用化妆品的人

    Makeup(int chioce,String girlName)
    {
        this.chioce = chioce;
        this.girlName = girlName;
    }
    @Override
    public  void run()
    {
      //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };
    
    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (chioce ==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 + "获得口红的锁");
            }
        }
    }
}

2.Lock解决死锁问题
//Lock锁
package ThreadPackage;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadLock implements  Runnable{
    private int ticketNum = 10;
    private  final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true)
        {

            try {
                lock.lock();
                //模拟延迟:放大问题的发生性.
                if(ticketNum>0)
                {
                    try {
                        Thread.sleep(1000);
                    }catch(Exception e)
                    {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "拿到第"+ ticketNum-- + "票");
                }
            }
            finally {
                lock.unlock();
            }
        }
    }
    public static void main(String[] args) {
        ThreadLock threadLock = new ThreadLock();
        new Thread(threadLock,"小明").start();
        new Thread(threadLock,"QIGO").start();
        new Thread(threadLock,"TEST").start();
    }
}
/*输出结果:
小明拿到第10票
小明拿到第9票
小明拿到第8票
小明拿到第7票
小明拿到第6票
小明拿到第5票
小明拿到第4票
小明拿到第3票
小明拿到第2票
小明拿到第1票

线程池

package ThreadPackage;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPool {
    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());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值