zoukankan      html  css  js  c++  java
  • Java多线程-创建多线程:继承Thread类&实现Runnable接口

    继承Thread类,创建多线程:

    MyThread.class
    package com.test.interview;
    
    public class MyThread extends Thread {
        private String name;
    
        public MyThread(String name) {
            this.name = name;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println("thread start:" + this.name + ",i=" + i);
            }
        }
    }
    ThreadDemo.class
    package com.test.interview;
    
    public class ThreadDemo {
        public static void main(String[] args) {
            MyThread mt = new MyThread("thread1");
            MyThread mt2 = new MyThread("thread2");
            MyThread mt3 = new MyThread("thread3");
            mt.start();
            mt2.start();
            mt3.start();
        }
    }
    

    实现Runnable接口,创建多线程:*(推荐这种方式)

    RunnableDemo.class
    package com.test.interview;
    
    public class RunnableDemo {
        public static void main(String[] args) {
            MyRunnable mr1 = new MyRunnable("Runnable1");
            MyRunnable mr2 = new MyRunnable("Runnable2");
            MyRunnable mr3 = new MyRunnable("Runnable3");
            Thread t1 = new Thread(mr1);
            Thread t2 = new Thread(mr2);
            Thread t3 = new Thread(mr3);
            t1.start();
            t2.start();
            t3.start();
        }
    }
    MyRunnable.class
    package com.test.interview;
    
    public class MyRunnable implements Runnable {
        private String name;
    
        public MyRunnable(String name) {
            this.name = name;
        }
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println("thread start:" + this.name + ",i=" + i);
            }
        }
    }
    

    Thread&Runnable的关系:  

  • 相关阅读:
    linux shell
    jsp应用
    JavaScript基础整理(2)
    Struts2验证框架实例
    一个Struts2的实例
    Java继承和多态实例
    VS2010webConfig配置
    html兼容性
    Linux 入门记录:一、命令行 Bash 的基本操作
    微信支付:curl 出错,错误码: 60
  • 原文地址:https://www.cnblogs.com/starstarstar/p/11221940.html
Copyright © 2011-2022 走看看