zoukankan      html  css  js  c++  java
  • 传统线程技术(一)

    一. 传统线程创建方法

    1. 覆盖Thread子类的run方法中编写详细代码

    2. 在传递给Thread的Runnable对象的run方法中编写详细代码


    二. 实现代码

    public class TraditionalThread {
    	public static void main(String[] args) {
    		// 方法1:直接new一个Thread的子类。让子类run方法覆盖父类的run方法
    		Thread thread1 = new Thread() {
    			@Override
    			public void run() {
    				while (true) {
    					try {
    						Thread.sleep(500);
    						System.out.println(Thread.currentThread().getName());
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    
    				}
    			}
    		};
    		thread1.start();  
    
    		// 方法2:给Thread类传一个实现了Runnable接口的类
    		Thread thread2 = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				while (true) {
    					try {
    						Thread.sleep(500);
    						System.out.println(Thread.currentThread().getName());
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    
    				}
    			}
    		});
    		thread2.start();
    	}
    }
    小知识:

    1. new Thread(){ 

        }   这样的写法事实上是创建了Thread的子类

    2. new Thread(new Runnable(){}){

        }   传递给Thread的參数事实上是Runnable的实现类对象


    三. 一个典型样例:

    请问以下的类是运行Runnable中的run方法还是Thread子类的方法?

    public class Test {
    	public static void main(String[] args) {
    		// 以下的代码将会执行Thread子类的run方法而不会执行runnable中的run方法
    		new Thread(new Runnable() {
    			@Override
    			public void run() {
    				while (true) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("Runnable:" + Thread.currentThread().getName());
    				}
    			}
    		}) {
    			@Override
    			public void run() {
    				while (true) {
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("Thread:" + Thread.currentThread().getName());
    				}
    			}
    		}.start();
    	}
    	
    	/**
    	 * Thread 类中的run方法
    	 * private Runnable target;
    	 * 
    	 * public void run() {
    	 *	  if (target != null) {
    	 *		  target.run();
    	 *	  }
    	 * }
    	 **/
    }
    答案是执行Thread子类的run方法。 由于它覆盖了父类的run方法,根本就不会执行到runnable的方法,即target.run()



  • 相关阅读:
    celery的使用和原理
    内核通知链
    数据流中的中位数
    二叉搜索树的后序遍历序列
    Javascript设计模式系统讲解与应用,JS设计模式详解
    微服务系列之ZooKeeper注册中心和Nacos注册中心
    微信小程序开发详解:小程序入门与实战-纯正商业级应用技术
    Java零基础该怎么去学习Java?学好Java应该如何去做?
    Flutter从入门到进阶实战携程网App项目详解
    Python升级3.6强力Django+杀手级Xadmin打造在线教育平台
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5172063.html
Copyright © 2011-2022 走看看