美文网首页
Java多线程基础一

Java多线程基础一

作者: 有斧头的IceBear | 来源:发表于2020-08-11 00:11 被阅读0次

    多线程创建的三种方式

    image6.png
    //创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
    //总结:注意,线程开启不一定立即执行,由CPU调度执行
    public class TestThread1 extends Thread {
        //ctrl + O 实现接口方法
        @Override
        public void run() {
            //20.for
            //run方法线程体
            for (int i = 0; i < 2000; i++) {
                System.out.println("我在看代码" + i);
            }
        }
    
        public static void main(String[] args) {
            //main线程,线程体
    
            //创建一个线程对象
            TestThread1 testThread1 = new TestThread1();
    
            //调用start()方法开启线程
            testThread1.start();
    
            for (int i = 0; i < 2000; i++) {
                System.out.println("我在学习多线程" + i);
            }
        }
    }
    
    //练习Thread,实现多线程同步下载图片
    public class TestThread2 implements Runnable {
    
        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://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596570590398&di=6cf133c3e5c91ecee840f29d138f8d3e&imgtype=0&src=http%3A%2F%2Fdepot.nipic.com%2Ffile%2F20150630%2F13214150_10223002228.jpg", "1.jpg");
            TestThread2 t2 = new TestThread2("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596570971558&di=732d6b6458d6be119c5b9ba8206b7a53&imgtype=0&src=http%3A%2F%2Fimg02.tooopen.com%2Fimages%2F20150612%2Ftooopen_sy_130061294574.jpg", "2.jpg");
            TestThread2 t3 = new TestThread2("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596571028542&di=68cb54fdea5116f7760c4d1f543b0f5c&imgtype=0&src=http%3A%2F%2Fhbimg.huabanimg.com%2F828f2b88f2105989fdc04e82b7dd21d68d34132b10a5a-c8Ei6W_fw658", "3.jpg");
    
            new Thread(t1).start();
            new Thread(t2).start();
            new Thread(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接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
    public class TestThread3 implements Runnable {
        //ctrl + O 实现接口方法
        @Override
        public void run() {
            //20.for
            //run方法线程体
            for (int i = 0; i < 2000; i++) {
                System.out.println("我在看代码" + i);
            }
        }
    
        public static void main(String[] args) {
            //创建runnable接口的实现类对象
    
            TestThread3 testThread3 = new TestThread3();
    
            //创建线程对象,通过线程对象来开启我们的线程,代理
            new Thread(testThread3).start();
    
            for (int i = 0; i < 2000; i++) {
                System.out.println("我在学习多线程" + i);
            }
        }
    }
    
    //多个线程同时操作同一对象
    //买火车票的例子
    
    //发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
    public class TestThread4 implements Runnable {
    
        //票数
        private int ticketNums = 10;
    
        @Override
        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();
        }
    }
    
    image1.png
    //线程创建方式三:实现callable接口
    /*
     callable的好处
     1.可以定义返回值
     2.可以抛出异常
     */
    public class TestCallable implements Callable<Boolean> {
        private String url;
        private String name;
    
        public TestCallable(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 {
            TestCallable t1 = new TestCallable("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596570590398&di=6cf133c3e5c91ecee840f29d138f8d3e&imgtype=0&src=http%3A%2F%2Fdepot.nipic.com%2Ffile%2F20150630%2F13214150_10223002228.jpg", "1.jpg");
            TestCallable t2 = new TestCallable("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596570971558&di=732d6b6458d6be119c5b9ba8206b7a53&imgtype=0&src=http%3A%2F%2Fimg02.tooopen.com%2Fimages%2F20150612%2Ftooopen_sy_130061294574.jpg", "2.jpg");
            TestCallable t3 = new TestCallable("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1596571028542&di=68cb54fdea5116f7760c4d1f543b0f5c&imgtype=0&src=http%3A%2F%2Fhbimg.huabanimg.com%2F828f2b88f2105989fdc04e82b7dd21d68d34132b10a5a-c8Ei6W_fw658", "3.jpg");
    
            //创建执行服务
            ExecutorService ser = Executors.newFixedThreadPool(3);
    
            //提交执行
            Future<Boolean> r1 = ser.submit(t1);
            Future<Boolean> r2 = ser.submit(t2);
            Future<Boolean> r3 = ser.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);
    
            //关闭服务
            ser.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方法出现问题");
            }
        }
    }
    
    image2.png
    //静态代理模式总结:
    //真实对象和代理对象都要实现同一个接口
    //代理对象要代理真实角色
    
    //好处:
        //代理对象可以做很多真实对象做不了的事情
        //真实对象专注做自己的事情
    
    public class StaticProxy {
        public static void main(String[] args) {
            You you = new You();  //你要结婚
    
            new Thread( ()-> System.out.println("hello world") ).start();
    
            new WeddingCompany(new You()).HappyMarry();
            WeddingCompany weddingCompany = new WeddingCompany(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;
        }
    
        @Override
        public void HappyMarry() {
            before();
            this.target.HappyMarry();  //这就是真是对象
            after();
        }
    
        private void before() {
            System.out.println("结婚之前,布置现场");
        }
    
        private void after() {
            System.out.println("结婚之后,收尾款");
        }
    
    }
    

    lambda

    image3.png image4.png image5.png
    /*
    推导lambda表达式
    */
    public class TestLambda1 {
        //3.静态内部类
        static class Like2 implements ILike {
            @Override
            public void lambda() {
                System.out.println("i like lambda2");
            }
        }
    
        public static void main(String[] args) {
            //创建一个接口对象
            ILike like = new Like();
            like.lambda();
    
            like = new Like2();
            like.lambda();
    
            //4.局部内部类
            class Like3 implements ILike {
                @Override
                public void lambda() {
                    System.out.println("i like lambda3");
                }
            }
    
            like = new Like3();
            like.lambda();
    
            //5.匿名内部类,没有类的名称,必须借助接口或者父类
            like = new ILike() {
                @Override
                public void lambda() {
                    System.out.println("i like lambda4");
                }
            };
            like.lambda();
    
            //6.用lambda简化
            like = () -> {
                System.out.println("i like lambda5");
            };
            like.lambda();
        }
    }
    
    //1.定义一个函数式接口
    interface ILike {
        void lambda(); //在接口里隐式声明为一个抽象方法
    }
    
    //2.实现类
    class Like implements ILike {
        @Override
        public void lambda() {
            System.out.println("i like lambda");
        }
    }
    
    public class TestLambda2 {
    
        public static void main(String[] args) {
    
            //1.lambda表示简化
            ILove love = (int a) -> {
                    System.out.println("i love you-->" + a);
            };
    
            //简化1.参数类型
            love = (a) -> {
                System.out.println("i love you-->" + a);
            };
    
            //简化2.简化括号
            love = a -> {
                System.out.println("i love you-->" + a);
            };
    
            //简化3.去掉花括号
            love = a -> System.out.println("i love you-->" + a);
            love.love(521);
    
            //总结:
                //lambda表达式只能有一行代码的情况下才能简化成一行,如果有多行,那么就用代码包裹。
                //前提是接口为函数式接口
                //多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
        }
    }
    
    interface ILove {
        void love(int a);
    }
    
    class Love implements ILove {
        @Override
        public void love(int a) {
            System.out.println("i love you-->" + a);
        }
    }
    

    相关文章

      网友评论

          本文标题:Java多线程基础一

          本文链接:https://www.haomeiwen.com/subject/skasdktx.html