• 多线程实现方式


    线程的生命周期有如下阶段:

    (1)新建状态(new)

    (2)运行状态(run)

     (3)阻塞状态(block)

    (4)死亡状态(dead)

    在实际实现线程时,java语言提供了3种实现方式:

    继承Thread类

    实现Runnable接口

    使用Time和TimeTask

    继承thread类

    package thread;
    /**功能:同时执行两个流程:main流程和自定义run方法流程。
    *换句话来说就是,该程序在执行两个线程,系统线程和自定义的线程。
    */
    public class FirstThread extends Thread{
     public static void main(String[] args){
      //初始化线程
      FirstThread ft = new FirstThread();
      //启动线程
      ft.start();
      try{
       for(int i = 0;i<10;i++){
        //延时一秒
        Thread.sleep(1000);
        System.out.println("main"+i);
       }
      }catch(Exception e){
       
      }
     }
     public void run(){
      try{
       for(int i = 0;i<10;i++){
        Thread.sleep(1000);
        System.out.println("run"+i);
       }
      }catch(Exception e){
       
      }
     }

    }

    实现runnable接口

    public class MyRunnableTest {
     public static void main(String[] args){
      MyRunnable mr = new MyRunnable();
      Thread t = new Thread(mr);
      t.start();
      try{
       for(int i = 0;i<10;i++){
        Thread.sleep(1000);
        System.out.println("main"+i);
       }
      }catch(Exception e){
       
      }
      
     }

    }


    public class MyRunnable implements Runnable{
     public void run(){
      try{
      for(int i = 0;i<10;i++){
       Thread.sleep(1000);
       System.out.println("run"+i);
      }
     }catch(Exception e){
      
     }

    }
    }

  • 相关阅读:
    how to pass a Javabean to server In Model2 architecture.
    What is the Web Appliation Archive, abbreviation is "WAR"
    Understaning Javascript OO
    Genetic Fraud
    poj 3211 Washing Clothes
    poj 2385 Apple Catching
    Magic Star
    关于memset的用法几点
    c++ 函数
    zoj 2972 Hurdles of 110m
  • 原文地址:https://www.cnblogs.com/belingzhong/p/2479807.html
Copyright © 2020-2023  润新知