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 创建线程

  • 相关阅读:
    【MSSQL】MSSQL还原单mdf文件报1813错误
    【JSP】JSP基础学习记录(二)—— JSP的7个动作指令
    【JSP】JSP基础学习记录(一)—— 基础介绍以及3个编译指令
    【Other】U盘FAT32转NTFS且无数据丢失
    python map()
    python关于分割与拼接的那些事
    python shutil.copy()用法
    python enumerate用法
    工作中遇到一些难题1_5
    廖雪峰读书笔记_文件读写总结_2016_12_23
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/6358222.html
Copyright © 2011-2022 走看看