zoukankan      html  css  js  c++  java
  • 多线程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());

     这行代码.

  • 相关阅读:
    asp.net 邮件发送,使用外部stmp服务器,呵呵!简单例子
    asp.net 新闻采集 简单示例
    JS 计算时间差
    textarea行尾输入多个空格不换行
    mac系统安装redis
    RSA 分段加解密【解决“不正确的长度”的异常】
    C# 获取指定进程的主窗口句柄
    .Net自定义控件之ToolboxBitmap元数据的设置
    提升 SharePoint 代码执行权限
    关于ThreadLocal的使用
  • 原文地址:https://www.cnblogs.com/liaokailin/p/3770815.html
Copyright © 2011-2022 走看看