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.
    		
    	}
    
    }
    

  • 相关阅读:
    在Eclipse中对包进行增删改查
    数据库中包的使用
    自定义函数执行动态sql语句
    用SQL语句创建四个表并完成相关题目-10月18日更新
    GUID简介
    设有一数据库,包括四个表:学生表(Student)、课程表(Course)、成绩表(Score)以及教师信息表(Teacher)。
    Java基础-服务器的发送和接收
    java基础-多线程执行
    Java基础-多线程编程-1.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
    Java基础-输入输出-3.编写BinIoDemo.java的Java应用程序,程序完成的功能是:完成1.doc文件的复制,复制以后的文件的名称为自己的学号姓名.doc。
  • 原文地址:https://www.cnblogs.com/wucg/p/1988373.html
Copyright © 2011-2022 走看看