Created
June 27, 2015 12:47
-
-
Save codetalks-new/b0f94142e95d630fc7e5 to your computer and use it in GitHub Desktop.
Java 并发多线程的等待结果完成的问题
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.SimpleDateFormat; | |
import java.util.*; | |
import java.util.concurrent.*; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.logging.*; | |
import java.util.logging.Formatter; | |
/** | |
* Created by banxi on 15/6/27. | |
*/ | |
class MyLogFormatter extends Formatter{ | |
private final Date date = new Date(); | |
@Override | |
public String format(LogRecord record) { | |
date.setTime(record.getMillis()); | |
String time = new SimpleDateFormat("HH:mm:ss S").format(date); | |
return String.format("[%s] [%s] %s\n",record.getLoggerName(), time,record.getMessage()); | |
} | |
} | |
public class Main { | |
public static final Random rand = new Random(47); | |
public static final Logger logger = Logger.getLogger("Main"); | |
static{ | |
Handler console = new ConsoleHandler(); | |
console.setFormatter(new MyLogFormatter()); | |
console.setLevel(Level.CONFIG); | |
for(Handler handler:logger.getParent().getHandlers()){ | |
logger.getParent().removeHandler(handler); | |
} | |
logger.addHandler(console); | |
} | |
final static int seconds [] = {1,2,3}; | |
final static AtomicInteger tIndex = new AtomicInteger(0); | |
public static boolean pingIp(String ip) { | |
int index = tIndex.getAndIncrement() % seconds.length; | |
int sleepSeconds = seconds[index]; | |
try { | |
logger.info("Start ping [" + ip + "]"); | |
Thread.sleep(sleepSeconds * 1000); | |
logger.info("End ping [" + ip + "]"); | |
return true; | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
logger.info("scanIp" + ip + " Failed"); | |
return false; | |
} | |
} | |
public static Map<String,Boolean> scanIpSync(String... ips){ | |
Map<String,Boolean> pinResult = new HashMap<>(); | |
for(String ip:ips){ | |
boolean r = pingIp(ip); | |
pinResult.put(ip, r); | |
} | |
return pinResult; | |
} | |
public static Map<String,Boolean> scanIpAsyncWithManulTaskList(String... ips){ | |
ExecutorService executor = Executors.newFixedThreadPool(ips.length); | |
List<ScanIpTask> tasks = new ArrayList<>(); | |
for(String ip: ips){ | |
ScanIpTask task = new ScanIpTask(ip); | |
tasks.add(task); | |
executor.execute(task); | |
} | |
Map<String,Boolean> pinResult = new HashMap<>(); | |
for(ScanIpTask task:tasks){ | |
try { | |
Boolean result = task.get(); | |
pinResult.put(task.ip,result); | |
logger.info("Task"+task.ip+" finished"); | |
} catch (InterruptedException | ExecutionException e) { | |
e.printStackTrace(); | |
pinResult.put(task.ip,false); | |
} | |
} | |
executor.shutdown(); | |
return pinResult; | |
} | |
public static Map<String,Boolean> scanIpAsyncWithRawThead(String... ips){ | |
List<ScanIpTask> tasks = new ArrayList<>(); | |
for(String ip: ips){ | |
ScanIpTask task = new ScanIpTask(ip); | |
tasks.add(task); | |
new Thread(task).start(); | |
} | |
Map<String,Boolean> pinResult = new HashMap<>(); | |
for(ScanIpTask task:tasks){ | |
try { | |
Boolean result = task.get(); | |
pinResult.put(task.ip,result); | |
logger.info("Task"+task.ip+" finished"); | |
} catch (InterruptedException | ExecutionException e) { | |
e.printStackTrace(); | |
pinResult.put(task.ip,false); | |
} | |
} | |
return pinResult; | |
} | |
public static List<Boolean> scanIpAsyncWithCompletionService(String... ips){ | |
ExecutorService executor = Executors.newFixedThreadPool(ips.length); | |
CompletionService<Boolean> completionService = new ExecutorCompletionService<Boolean>(executor); | |
for(String ip: ips){ | |
PingIpTask task = new PingIpTask(ip); | |
completionService.submit(task); | |
} | |
List<Boolean> results = new ArrayList<>(); | |
for(int t = 0, n = ips.length; t < n; t++){ | |
Boolean result = null; | |
try { | |
Future<Boolean> future = completionService.take(); | |
result = future.get(); | |
logger.info("Finish "); | |
} catch (InterruptedException | ExecutionException e) { | |
e.printStackTrace(); | |
results.add(false); | |
} | |
results.add(result); | |
} | |
executor.shutdown(); | |
return results; | |
} | |
static class PingIpTask implements Callable<Boolean>{ | |
String ip; | |
public PingIpTask(String ip){ | |
this.ip = ip; | |
} | |
@Override | |
public Boolean call() throws Exception { | |
return pingIp(ip); | |
} | |
} | |
static class ScanIpTask extends FutureTask<Boolean>{ | |
String ip; | |
public ScanIpTask(final String ip) { | |
super(new Callable<Boolean>() { | |
@Override | |
public Boolean call() throws Exception { | |
return pingIp(ip); | |
} | |
}); | |
this.ip = ip; | |
} | |
} | |
public static void main(String[] args) { | |
String [] ips = {"192.1","192.2", "192.3","192.4","192.5","192.6","192.7","192.8","192.9","192.10"}; | |
long start = System.currentTimeMillis(); | |
Map<String,Boolean> pinResult = scanIpAsyncWithManulTaskList(ips); | |
// List<Boolean> pinResult = scanIpAsyncWithCompletionService(ips); | |
long end = System.currentTimeMillis(); | |
long spendMillis = (end - start); | |
logger.info("Ping All IP spend time=" + spendMillis + " ms"); | |
logger.info("Ping Result " + pinResult); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment