• 多线程01-线程基础


    线程的两种实现方式 

          继承Thread类

    Thread thread = new Thread(){
    			@Override
    			public void run() {
    				while(true){
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("1:" + Thread.currentThread().getName());
    					System.out.println("2:" + this.getName());
    				}
    			}
    		};
    		thread.start();
    

           实现Runnable接口

    	Thread thread2 = new Thread(new Runnable(){
    			@Override
    			public void run() {
    				while(true){
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("1:" + Thread.currentThread().getName());
    
    				}				
    				
    			}
    		});
    		thread2.start();
    

      

    要注意的是: 实现Runnable接口类实质上不是一个线程实现类 ,是在new Thead(实现Runnable接口类).start() 的时候才真正的调用线程类 Runnable接口只是覆盖了run()方法的实现.

    例子

    		new Thread(
    				new Runnable(){
    					public void run() {
    						while(true){
    							try {
    								Thread.sleep(500);
    							} catch (InterruptedException e) {
    								e.printStackTrace();
    							}
    							System.out.println("runnable :" + Thread.currentThread().getName());
    
    						}							
    					}
    				}
    		){
    			public void run() {
    				while(true){
    					try {
    						Thread.sleep(500);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println("thread :" + Thread.currentThread().getName());
    
    				}	
    			}
    		}.start();
    		
    

      

       上面的例子最终允许的是哪个run方法呢?

      分析:new Runnable(){} 是Runnable接口的匿名内部类,  new Thread( new Runnable(){}) 实质上是创建了一个Thead的类对象  ,  new Thread( new Runnable(){}) {}则为Thead的一个

    匿名内部类,覆写了run方法  那么最终调用的肯定是匿名内部类中的run方法   即: 执行

    System.out.println("thread :" + Thread.currentThread().getName());

     这行代码.

  • 相关阅读:
    第3次实践作业
    第2次实践作业
    第1次实践作业
    2019 SDN大作业
    第05组 Beta版本演示
    个人作业——软件工程实践总结&个人技术博客
    个人作业——软件评测
    Springboot项目部署到云服务器(Ubuntu 18.04)
    结对第二次作业——某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
  • 原文地址:https://www.cnblogs.com/liaokailin/p/3770815.html
Copyright © 2020-2023  润新知