zoukankan      html  css  js  c++  java
  • 线程和线程池的使用

    参考:http://www.cnblogs.com/dolphin0520/p/3932921.html

    1、线程:循环新建10个线程

    注意:final定义的变量才能在run()方法里使用 

    package com.test;
    
    public class TestThread {
    
    	public static void main(String[] args) {
    		for(int i =0; i <9; i++){
    			//final变量才能传到run()方法里
    			final int task = i;	
    			new Thread(new Runnable(){	
    				@Override
    				public synchronized void run() {
    					System.out.println("task:" + task);
    				}
    				
    			}).start();
    		}
    		
    	}
    	
    }
    

    2、线程池

    不提倡直接使用ThreadPoolExecutor,Java通过Executors提供四种线程池,分别为:


    (1)newCachedThreadPool

      创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
    (2)newFixedThreadPool

      创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
    (3)newScheduledThreadPool

      创建一个定长线程池,支持定时及周期性任务执行。
    (4)newSingleThreadExecutor

      创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。

    如下是newFixedThreadPool的使用实例:

    package com.test;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class TestExcutor {
    
    	public static void main(String[] args) {
    		//线程池接口:ExecutorService
    		ExecutorService fixThreadPool = Executors.newFixedThreadPool(5);
    		for(int i=1; i<=5; i++){
    			final int task =i;
    			fixThreadPool.execute(new Runnable(){
    
    				@Override
    				public synchronized void run() {
    					for(int j=1; j<=3;j++){
    						System.out.println(Thread.currentThread().getName() + "  " +"task:" + task + "   times:" +j);
    					}
    				}
    				
    			});
    		}
    		fixThreadPool.shutdown();
    		
    	}
    	
    }
    

      

  • 相关阅读:
    使用 SQL Server 2008 数据类型-xml 字段类型参数进行数据的批量选取或删除数据
    启用Windows 7/2008 R2 XPS Viewer
    Office 2010培训资料
    WCF WebHttp Services in .NET 4
    ASP.NET MVC 2示例Tailspin Travel
    .NET 4.0 的Web Form和EF的例子 Employee Info Starter Kit (v4.0.0)
    连任 2010 年度 Microsoft MVP
    MIX 10 Session下载
    Microsoft Silverlight Analytics Framework
    Windows Azure入门教学
  • 原文地址:https://www.cnblogs.com/Donnnnnn/p/7676699.html
Copyright © 2011-2022 走看看