zoukankan      html  css  js  c++  java
  • 启动线程的方法

    在线程的Tread对象上调用start()方法,而不是run()或者别的方法。

    在调用Start方法之前,线程出于新状态中,新状态是指有一个Thread对象!但还没有一个真正的线程。

    在调用start之后发生了一系列复杂的事情

    启动新的执行线程(具有新的调用栈)

    该线程从新状态转移到可运行状态

    当该线程获得机会执行时,其目标run()方法将运行

    在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。

    对于直接继承Thread的类来说,代码大致框架是:

    class 类名 extends Thread{
    方法1;
    方法2;
    …
    public void run(){
    // other code…
    }
    属性1;
    属性2;
    …
     
    }
    class hello extends Thread {
     
        public hello() {
     
        }
     
        public hello(String name) {
            this.name = name;
        }
     
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(name + "运行     " + i);
            }
        }
    
    public static void main(String[] args) {
            hello h1=new hello("A");
            hello h2=new hello("B");
            h1.start();
            h2.start();
        }
    
     private String name;
    }

    线程的运行需要本地操作系统的支持。所以需要使用start()而不是直接使用run()。

    通过实现Runnable接口:

    class 类名 implements Runnable{
    方法1;
    方法2;
    …
    public void run(){
    // other code…
    }
    属性1;
    属性2;
    …
     
    }
    class hello implements Runnable {
     
        public hello() {
     
        }
     
        public hello(String name) {
            this.name = name;
        }
     
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(name + "运行     " + i);
            }
        }
     
        public static void main(String[] args) {
            hello h1=new hello("线程A");
            Thread demo= new Thread(h1);
            hello h2=new hello("线程B");
            Thread demo1=new Thread(h2);
            demo.start();
            demo1.start();
        }
     
        private String name;
    }

    【可能的运行结果】:

    线程A运行     0

    线程B运行     0

    线程B运行     1

    线程B运行     2

    线程B运行     3

    线程B运行     4

    线程A运行     1

    线程A运行     2

    线程A运行     3

    线程A运行     4

    尽量去实现Runnable接口

  • 相关阅读:
    23种设计模式之单例模式
    Java基础之IO技术(一)
    spark利用yarn提交任务报:YARN application has exited unexpectedly with state UNDEFINED
    linux配置了dns后导致mysql远程连接慢问题
    发布网站后localhost可以访问ip不行
    electron编译sqlite3
    vscode文件树缩进
    js判断浏览器类型
    vue可复用slide动画
    vscode使用formate格式化less遇到的坑
  • 原文地址:https://www.cnblogs.com/yanz/p/3937792.html
Copyright © 2011-2022 走看看