zoukankan      html  css  js  c++  java
  • 【多线程 2】常见的多线程创建方式

    导读:创建多线程,主要是有3种方式。而这三种方式,又可以简单的分为:无回执结果、有回执结果。

    一、直接继承Thread类

    <span style="font-family:KaiTi_GB2312;font-size:18px;">package Angel;
    
    public class CreateThread extends Thread {
    
    	//对run方法进行重写
    	public void run(){
    		System.out.println("继承Thread创建:" + Thread.currentThread().getName());
    		System.out.println("继承Thread创建:" + this.getName());
    	}
    	public static void main(String[] args) {
    		new CreateThread().start();
    	}
    }
    </span>

    二、实现Runnable接口

    <span style="font-family:KaiTi_GB2312;font-size:18px;">package Angel;
    
    public class CreateThread implements Runnable {
    
    	//对run方法进行重写
    	public void run(){
    		System.out.println("实现Runnable接口创建:" + Thread.currentThread().getName());
    	}
    	public static void main(String[] args) {
    		
    		CreateThread newThread=new CreateThread();
    		new Thread(newThread,"Thread 1").start();
    		new Thread(newThread,"Thread 2").start();
    	}
    }</span>

    备注:在实际应用的时候,通常也可以写作:

    <span style="font-family:KaiTi_GB2312;font-size:18px;">package Angel;
    
    public class CreateThread {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    
    		Thread thread = new Thread() {
    			@Override
    			public void run() {
    				System.out.println("创建Thread对象:" + Thread.currentThread().getName());
    				System.out.println("创建Thread对象:" + this.getName());
    			}
    		};
    		thread.start();
    
    		Thread thread2 = new Thread(new Runnable() {
    			@Override
    			public void run() {
    				System.out.println("创建Runnable对象:" + Thread.currentThread().getName());
    			}
    		});
    		thread2.start();
    	}
    }
    </span>


    以上的两种方式,是没有回执结果的创建方式,也是常用的创建方式。下面介绍一种可以返回结果的线程的创建方法


    三、使用Callable和Future

    <pre name="code" class="java"><span style="font-family:KaiTi_GB2312;font-size:18px;">package Angel;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    public class CreateThread implements Callable<String>  
    {  
      
        public static void main(String[] args)  
        {  	
        	System.out.println("主线程开始");
        
        	CreateThread ctt = new CreateThread();  
            FutureTask<String> ft = new FutureTask<>(ctt);  
            new Thread(ft,"开始子线程").start();  
            try  
            {  
                System.out.println("子线程的返回值:"+ft.get());  
            } catch (InterruptedException e)  
            {  
                e.printStackTrace();  
            } catch (ExecutionException e)  
            {  
                e.printStackTrace();  
            }  
      
            System.out.println("主线程结束");
        }  
      
        @Override  
        public String call() throws Exception  
        {  
            System.out.println(Thread.currentThread().getName());  
            return "successful";  
        }  
      
    } </span>

    
    
    在应用中的写法:

    <span style="font-family:KaiTi_GB2312;font-size:18px;">package Angel;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class CreateThread {
    
    	public static void main(String[] args) {
    		ExecutorService threadPool = Executors.newSingleThreadExecutor();
    		Future<String> future = threadPool.submit(new Callable<String>() {
    			public String call() throws Exception {//线程执行结果
    				Thread.sleep(2000);
    				return "hello";
    			};
    		});
    		System.out.println("等待结果");
    		try {
    			System.out.println("拿到结果:" + future.get());
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }</span>

    四、总结

    多线程的创建方式,主要就包括以上的集中。第三种方式则在JDK1.5以后开始使用。总体说来,继承接口的实现,优势是可以同时继承其他类,可以共享实例属性。但是在获取当前线程的时候,则需要使用Thread.currentThread方法,而不能直接使用this获取!接下来,介绍线程通信的问题!


  • 相关阅读:
    【python】第一个爬虫:用requests库爬取网页内容
    【python】UDP协议编程
    【python】体育竞技分析:预测球队比赛成绩
    【python】手绘图制作
    【python】成绩表雷达图
    【python】numpy库和matplotlib库学习笔记
    【python】PIL库之图片处理
    【python】PIL库学习总结
    【python】利用jieba中文分词进行词频统计及生成词云
    汉诺塔问题
  • 原文地址:https://www.cnblogs.com/hhx626/p/7534632.html
Copyright © 2011-2022 走看看