• 001 线程的创建和启动


    一 . 概述

    在jdk之中包含两种线程的创建方式,并统一使用start()方法进行线程的启动.


    二 .继承Thread 来创建线程

    public class CreateThread {
        public static void main(String[] args) {
            //创建线程一并完成任务一
                    new Thread() {
                        @Override
                        public void run() {
                            task1();
                        }
                        
                    }.start();
                    
                    new Thread() {
                        @Override
                        public void run() {
                            task2();
                        };
                    }.start();
        }
    
        public static void task1() {
            for(int i=0;i<20;i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("task1===>"+i);
            }
        }
        public static void  task2() {
            for(int i=0;i<20;i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("task2===>"+i);
            }
        }
    }

    三 ,实现Runnable 接口创建线程

    public class UseRunnable {
        public static void main(String[] args) {
            new Thread(new Runnable() {
                public void run() {
                    task1();
                }
            }).start();
            
            new Thread(new Runnable() {
                public void run() {
                    task2();
                }
            }).start();
        }
        public static void task1() {
            for(int i=0;i<20;i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("task1===>"+i);
            }
        }
        public static void  task2() {
            for(int i=0;i<20;i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("task2===>"+i);
            }
        }
    }

    四 .两种方法的比较

    [1] 两种方式其实是一种方式,只不过使用Runnable接口来抽离线程逻辑单元.

    [2] 我们一般情况下更喜欢使用Runnable的方式来创建线程.

    [3] Runnable的方式类似于策略设计模式.

    总结 : 在下面我们说一下策略设计模式.

  • 相关阅读:
    Git -- 分支管理简介
    Git -- 从远程库克隆
    Git -- 添加远程仓库
    C# sha256 加密算法
    如何将IOS版本的更新下载文件指向到自己的服务器
    如何让windows服务器IIS支持.apk/.ipa文件下载
    vistual studio 去除 git 源代码 绑定
    Redis 环境搭建与使用(C#)
    c#图片添加水印
    C#使用WSDL服务总结
  • 原文地址:https://www.cnblogs.com/trekxu/p/8969250.html
Copyright © 2020-2023  润新知