• 传统线程技术(一)


    一. 传统线程创建方法

    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()



  • 相关阅读:
    xray与burp联动被动扫描
    Xray简单使用教程
    xray安装证书进行http以及https扫描
    brup安装证书抓取https
    Apache Solr JMX服务 RCE 漏洞复现
    pocsuite3使用教程
    Apache-Tomcat-Ajp漏洞(CVE-2020-1938)漏洞复现(含有poc)
    CVE-2019-0193:Apache Solr 远程命令执行漏洞复现
    如何在kalilinux上安装docker
    如何在windows10家庭版上搭建docker
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5172063.html
Copyright © 2020-2023  润新知