• 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);
        }
    }
  • 相关阅读:
    iOS8及以后 地图定位当前城市
    UITextView换行问题解决办法
    使用七牛上传图片代码,导入文件常遇问题解决方法
    CocoaPods安装和使用
    Xcode7真机测试
    Label 添加表情图片
    TTTAttributedLabel使用介绍(转)
    带有中文的url和NSString中文的转换
    正则表达式的使用 选取有用数据
    导航网格配置笔记
  • 原文地址:https://www.cnblogs.com/samwang88/p/8177695.html
Copyright © 2020-2023  润新知