码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程Thread使用匿名内部类创建的两种方式

时间:2018-06-17 16:02:16      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:rgs   star   style   ide   匿名   子类   tar   方法   ack   

     匿名内部类实现线程的两种方式:

第一种方式:

  • 1.继承Thread类
  • 2.重写run方法
  • 3.将要执行的代码写在run方法中

第二种方式:

  • 1.将Runnable的子类对象传递给Thread的构造方法
  • 2.重写run方法
  • 3.将执行的代码写在run方法中,最后我们开启线程
package com.yyx.thread;

/**
 * 匿名内部类创建线程 yyx 2018年2月4日
 */
public class AnonymousThread {
    public static void main(String[] args) {
        // 继承thread类实现多线程
        new Thread() {
            public void run() {
                for (int x = 0; x < 50; x++) {
                    System.out.println(Thread.currentThread().getName() + "--"
                            + x);
                }
            }
        }.start();
        // 实现runnable借口,创建多线程并启动
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int x = 0; x < 50; x++) {
                    System.out.println(Thread.currentThread().getName() + "--"
                            + x);
                }
            }
        }) {
        }.start();
    }
}

 

Java多线程Thread使用匿名内部类创建的两种方式

标签:rgs   star   style   ide   匿名   子类   tar   方法   ack   

原文地址:https://www.cnblogs.com/xianya/p/9192923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!