zoukankan      html  css  js  c++  java
  • Java线程的创建及启动

    1.继承Thread类,重写该类的run()方法。

    package samTest;
    
    import java.util.Scanner;
    
    /**
     * Created by Sam on 2018-01-02.
     */
    public class ThreadTest {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            for (int i = 0; i < 3; i++) {
                int flag = in.nextInt();
                Thread t = new MyThread(flag);
                t.start();
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
    }
    
    
    class MyThread extends Thread {
        private Integer threadFlag;
    
        public MyThread(Integer threadFlag) {
            this.threadFlag = threadFlag;
        }
    
        @Override
        public void run() {
            System.out.println(threadFlag);
        }
    }

    2.实现Runnable接口,并重写该接口的run()方法,该run()方法同样是线程执行体,创建Runnable实现类的实例,并以此实例作为Thread类的target来创建Thread对象,该Thread对象才是真正的线程对象。

    package samTest;
    
    import java.util.Scanner;
    
    /**
     * Created by Sam on 2018-01-02.
     */
    public class ThreadTest {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            for (int i = 0; i < 3; i++) {
                int flag = in.nextInt();
                Runnable r = new MyRunnable(flag);
                Thread t = new Thread(r);
                t.start();
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
    }
    
    class MyRunnable implements Runnable {
        private Integer threadFlag;
    
        public MyRunnable(Integer threadFlag) {
            this.threadFlag = threadFlag;
        }
    
        public void run() {
            System.out.println(threadFlag);
        }
    }
  • 相关阅读:
    JAVA基础知识|HTTP协议-两个特性
    JAVA基础知识|TCP/IP协议
    Spring Cloud|高可用的Eureka集群服务
    Hadoop环境搭建|第四篇:hive环境搭建
    C#中Func与Action的理解
    C# lambda表达式
    WPF ControlTemplate
    sublime text3插件安装及使用
    Dev Express之ImageComboBoxEdit,RepositoryItemImageComboBox使用方式
    SQL查询结果增加序列号
  • 原文地址:https://www.cnblogs.com/samwang88/p/8177695.html
Copyright © 2011-2022 走看看