zoukankan      html  css  js  c++  java
  • Java Concurrency

    ConcurrencyThe issue that can make a difference is blocking. If one task in your program is unable to continuebecause of some condition outside of the control of the program(typically I/O), we say that the taskor the thread blocks. Without concurrency, the whole program comes to a stop until the external condition changes. If the program is written using concurrency, however, the other tasks in the programcan toncinue to execute when one task is blocked, so the program continues to move forward.
    A Runnable is a separate task that performs work, but it doesn't reurn a value. If you want the task to produce a value when it's done,

    you can implement the Callable interface rather than the Runnable interface. Callable, introduced in Java SE5, is a generic with a type parameter representing the return value from the method call() (instead of run()), and must be invoked using an ExecutorService submit() method. Here's a simple example.

    //LiftOff.java
    
    package threaddemo;
    
    public class LiftOff implements Runnable {
    
    	protected int countDown=10;
    	public LiftOff() {
    	}
    	public LiftOff(int countDown) {
    		this.countDown=countDown;
    	}
    	
    	private static int taskID=0;
    	public int id=taskID++;
    
    	public String status() {
    		return "#" + id + " is at " + countDown;
    	}
    	
    	@Override
    	public void run() {
    		while(countDown-->0){
    			System.out.println(status());
    			Thread.yield();
    		}
    	}
    
    }
    //TaskWithResult.java
    
    package threaddemo;
    
    import java.util.concurrent.Callable;
    
    public class TaskWithResult implements Callable<String> {
    	private static int cnt=0;
    	private final int num=cnt++;
    	private int i;
    	
    	public TaskWithResult() {
    	}
    
    	public TaskWithResult(int i) {
    		this.i = i;
    	}
    
    	@Override
    	public String call() throws Exception {
    		return "My Thrad ID:"+num+"返回的字符串为:" + i;
    	}
    	
    }
    
    //Test.java
    
    package threaddemo;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;
    
    public class Test {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) throws Exception {
    		
    //		Thread thread=new Thread(new LiftOff());
    //		thread.start();
    //		System.out.println("Main End");		
    		////////////////////////////////////////		
    //		for (int i = 0; i < 5; i++) {
    //			Thread thread = new Thread(new LiftOff());
    //			thread.start();
    //		}
    //		System.out.println("Main End");
    		
    		///////////////////////////////////////////
    		//ExecutorService svs = Executors.newCachedThreadPool();
    //		ExecutorService svs = Executors.newFixedThreadPool(5);
    //		for (int i = 0; i < 5; i++) {
    //			Thread thread = new Thread(new LiftOff());
    //			svs.execute(thread);			
    //		}
    //		svs.shutdown();
    //
    		/////////////////////////////////////////
    		
    		ExecutorService svs = Executors.newCachedThreadPool();
    		List<Future<String>> result=new ArrayList<Future<String>>();
    		for(int i=0;i<10;i++){
    			result.add( svs.submit(new TaskWithResult(i)) );
    			//Old-style:
    			//Thread.sleep(100);
    			//Java SE5/6-style:
    			TimeUnit.MILLISECONDS.sleep(100);
    		}
    		for (Future<String> future : result) {
    			try {
    				System.out.println(future.get());
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			} catch (ExecutionException e) {
    				e.printStackTrace();
    			}
    			finally{
    				svs.shutdown();
    			}
    		}
    //		The submit() method produces a Future object, parameterized for 
    //		the particular type of result returned by the Callable. You can query
    //		the Future with isDone() to see if it has completed. When the task
    //		is completed and has a result, you can call get() to fetch the result.
    //		You can simply call get() without checking isDone(), in which case
    //		get() will block until the result is ready. You can also call get()
    //		with a timeout, or isDone() to see if the task has completed, before 
    //		trying to call get() to fetch the result.
    		
    	}
    
    }
    

  • 相关阅读:
    listener中@Autowired无法注入bean的一种解决方法
    PBKDF2加密的实现
    springmvc集成shiro后,session、request是否发生变化
    java加密解密工具类
    springMVC中controller层方法中使用private和public问题
    密码强度正则表达式 – 必须包含大写字母,小写字母和数字,至少8个字符等
    Java判断两个时间相差的天数
    Java中Date、String、Calendar类型之间的转化
    JavaScript前端和Java后端的AES加密和解密(转)
    JS前端加密JAVA后端解密详解
  • 原文地址:https://www.cnblogs.com/wucg/p/1988373.html
Copyright © 2011-2022 走看看