zoukankan      html  css  js  c++  java
  • 【通过匿名内部类方式使用多线程】

    new Thread(){代码…}.start();

    new Thread(new Runnable(){代码…}).start();

    例子1:

    匿名内部类的格式:

      new 类名或者接口名() {

        重写方法;

      };

    本质:是该类或者接口的子类对象。

    package com.test;
    
    public class ThreadTest {
    
        public static void main(String[] args) {
            /**继承Thread类来实现多线程*/
            new Thread() {
                public void run() {
                    for (int x = 0; x < 10; x++) {
                        System.out.println(Thread.currentThread().getName() + ":"
                                + x);
                    }
                }
            }.start();
    
            /**实现Runnable接口来实现多线程*/
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int x = 0; x < 10; x++) {
                        System.out.println(Thread.currentThread().getName() + ":"
                                + x);
                    }
                }
            }) {
            }.start();
    
            /**更有难度的*/
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int x = 0; x < 100; x++) {
                        System.out.println("hello" + ":" + x);
                    }
                }
            }) {
                public void run() {
                    for (int x = 0; x < 10; x++) {
                        System.out.println("world" + ":" + x);
                    }
                }
            }.start();
        }
    
    }

    执行结果:

    Thread-0:0
    Thread-0:1
    Thread-0:2
    Thread-0:3
    Thread-0:4
    Thread-0:5
    Thread-0:6
    Thread-0:7
    Thread-0:8
    Thread-0:9
    Thread-1:0
    Thread-1:1
    Thread-1:2
    Thread-1:3
    Thread-1:4
    Thread-1:5
    Thread-1:6
    Thread-1:7
    Thread-1:8
    Thread-1:9
    world:0
    world:1
    world:2
    world:3
    world:4
    world:5
    world:6
    world:7
    world:8
    world:9
    终身学习者
  • 相关阅读:
    js 构造函数 constructor
    js foreach和map区别
    js 静态方法和实例方法
    学习知识点总结(es6篇)
    java1.5新特性(转)
    21 Managing the Activity Lifecycle
    Java进阶Collection集合框架概要·16
    Java进阶核心之集合框架Map下集·18
    Java进阶核心之集合框架Set·19
    Java进阶核心之集合框架List·17
  • 原文地址:https://www.cnblogs.com/zuixinxian/p/9576529.html
Copyright © 2011-2022 走看看