zoukankan      html  css  js  c++  java
  • Java多线程(二)、启动一个线程的3种方式

    package org.study.thread;
    
    /**
     * 启动一个线程的3种方式
     */
    public class TraditionalThread {
    
    	public static void main(String[] args) {
    		// 1. 继承自Thread类(这里使用的是匿名类)
    		new Thread(){
    			@Override
    			public void run() {
    				while(true) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("threadName: " + Thread.currentThread().getName());
    				}
    			};
    		}.start();
    		
    		// 2. 实现Runnable接口(这里使用的是匿名类)
    		new Thread(new Runnable() {
    			@Override
    			public void run() {
    				while(true) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("threadName: " + Thread.currentThread().getName());
    				}
    			}
    		}).start();
    		
    		// 3.即实现Runnable接口,也继承Thread类,并重写run方法
    		new Thread(new Runnable() {
    			@Override
    			public void run() {	// 实现Runnable接口
    				while(true) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("implements Runnable thread: " + Thread.currentThread().getName());
    				}
    			}
    		}) {	// 继承Thread类
    			@Override
    			public void run() {
    				while(true) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("extends Thread thread: " + Thread.currentThread().getName());
    				}
    			}
    		}.start();
    	}
    }


    执行结果:

    threadName: Thread-0

    threadName: Thread-1

    extends Thread thread: Thread-2

    threadName: Thread-1

    threadName: Thread-0

    extends Thread thread: Thread-2

    threadName: Thread-1

    threadName: Thread-0

    extends Thread thread: Thread-2

    。。。


  • 相关阅读:
    阿里面试后的问题总结
    Spring IOC源码实现流程
    Spring Aop源码分析
    SpringCloud的分布式配置及消息总线
    阿里java编码规范考试总结
    压缩文件的压缩时候中文乱码码
    mybatis的时间比较 xml 及不解析<=的写法
    批量插入一张表的数据,并且生成不同的uuid 字符截取 批量更新 去除重复数据
    Redis集群的搭建
    Python 之 基础知识(二)
  • 原文地址:https://www.cnblogs.com/xyang0917/p/4172511.html
Copyright © 2011-2022 走看看