zoukankan      html  css  js  c++  java
  • Java创建线程的三种方式

    1.继承Runnable接口

    package test;
    class RunnableDemo implements Runnable{
        private Thread t;
        private String threadName;
        
        RunnableDemo(String name){
            threadName=name;
            System.out.println("Creating "+name);
        }
        public void run(){
            System.out.println("Running "+threadName);
            try{
                for(int i=4;i>0;i--){
                    System.out.println("Thread: "+threadName+" "+i);
                    Thread.sleep(50);
                }
            }
            catch(InterruptedException e){
                System.out.println("Thread "+threadName+" Excepted");
            }
            System.out.println("Thread "+threadName+" Exiting");
        }
        public void start(){
            System.out.println("Starting "+threadName);
            if(t==null){
                t=new Thread(this,threadName);
                t.start();
            }
        }
    }
    public class HelloWorld {
        public static void main(String []args) {
            RunnableDemo R1=new RunnableDemo("thread1");
            R1.start();
            RunnableDemo R2=new RunnableDemo("thread2");
            R2.start();
        }
    }

    2.继承Thread类

    package test;
    class ThreadDemo extends Thread{
        private Thread t;
        private String threadName;
        
        ThreadDemo(String name){
            threadName=name;
            System.out.println("Creating "+name);
        }
        public void run(){
            System.out.println("Running "+threadName);
            try{
                for(int i=4;i>0;i--){
                    System.out.println("Thread: "+threadName+" "+i);
                    Thread.sleep(50);
                }
            }
            catch(InterruptedException e){
                System.out.println("Thread "+threadName+" Excepted");
            }
            System.out.println("Thread "+threadName+" Exiting");
        }
        public void start(){
            System.out.println("Starting "+threadName);
            if(t==null){
                t=new Thread(this,threadName);
                t.start();
            }
        }
    }
    public class HelloWorld2 {
        public static void main(String []args) {
            ThreadDemo T1=new ThreadDemo("thread1");
            T1.start();
            ThreadDemo T2=new ThreadDemo("thread2");
            T2.start();
        }
    }

    3.通过 Callable 和 Future 创建线程

  • 相关阅读:
    Android EditText内容监听
    Android模仿QQ空间图片上传——原理
    PHP新手入门1——表单
    linux下ftp常用命令
    TextView所有属性
    iOS开发-删除字典中的null
    去除导航栏下方的横线
    应用的启动视图 LauchView
    App所需申请资料
    应用本地化
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/6358222.html
Copyright © 2011-2022 走看看