码迷,mamicode.com
首页 > 编程语言 > 详细

core java

时间:2016-08-23 16:40:59      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

 

ConsoleTest,这个程序如果在IDE里运行就会因无法获得控制台而报错

技术分享
import java.io.Console;

public class ConsoleTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Console console=System.console();
        String username=console.readLine("username:");
        char[] pwd=console.readPassword("password:");
        System.out.println(username);
        System.out.println(pwd);
    }

}
View Code

技术分享

ProxyTest

技术分享
package corejava;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Random;
class TraceHandler implements InvocationHandler{
    private Object target;
    public TraceHandler (Object t)
    {
        target=t;
    }
    
    public Object invoke(Object proxy,Method m,Object[] args) throws Throwable{
        System.out.print(target);
        System.out.print("."+m.getName()+"(");
        if(args!=null){
            for(int i=0;i<args.length;i++){
                System.out.print(args[i]);
                if(i<args.length-1){
                    System.out.println(",");
                }
            }
        }
        System.out.println(")");
        return m.invoke(target,args);
    }
}
public class ProxyTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object[]elements=new Object[1000];
        
        for(int i=0;i<elements.length;i++){
            Integer value=i+1;
            InvocationHandler handler=new TraceHandler(value);
            //null表示使用默认的类加载器
            Object proxy=Proxy.newProxyInstance(null, new Class[]{Comparable.class}, handler);
            elements[i]=proxy;
        }
        
        Integer key=new Random().nextInt(elements.length)+1;
        
        int result =Arrays.binarySearch(elements, key);
        
        if(result>0){
            System.out.println(elements[result]);
        }
    }
}
View Code

 

输出:

500.compareTo(159)
250.compareTo(159)
125.compareTo(159)
187.compareTo(159)
156.compareTo(159)
171.compareTo(159)
163.compareTo(159)
159.compareTo(159)
159.toString()
159

 

BlockingQueueTest阻塞队列实现同步

技术分享
package corejava;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);
        System.out.println("Enter base direction");
        String directory =in.nextLine();
        System.out.print("Enter keyword :");
        String keyword = in.nextLine();
        final int FILE_QUEUE_SIZE=10;
        final int SEARCH_THREADS=100;
        
        BlockingQueue queue=new  ArrayBlockingQueue<>(FILE_QUEUE_SIZE);
        FileEnumerationTask enumrator=new FileEnumerationTask(queue,new File(directory));
        new Thread(enumrator).start();
        for(int i=0;i<SEARCH_THREADS;i++){
            new Thread(new SearchTask(queue,keyword)).start();
        }
    }
}
class FileEnumerationTask implements Runnable{
    public static File DUMMY=new File("");
    private BlockingQueue<File> queue;
    private File strartingDirectory;
    
    public FileEnumerationTask(BlockingQueue<File> queue,File strartingDirectory){
        this.queue=queue;
        this.strartingDirectory=strartingDirectory;
    }
    
    public void run(){
        try{
            enumrator(strartingDirectory);
            queue.put(DUMMY);
        }catch(Exception e){}
    }
    public void enumrator(File directory) throws InterruptedException{
        File[] files=directory.listFiles();
        for(File file:files){
            if(file.isDirectory()){
                enumrator(file);
            }else{
                queue.put(file);
            }
        }
    }
}
class SearchTask implements Runnable{
    private BlockingQueue<File> queue;
    private String keyword;
    
    public SearchTask(BlockingQueue<File> queue,String keyword){
        this.queue=queue;
        this.keyword=keyword;
    }
    public void run(){
        try{
            boolean done=false;
            while(!done){
                File file=queue.take();
                if(file==FileEnumerationTask.DUMMY){
                    queue.put(file);
                    done=true;
                }else{
                    search(file);
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        catch(InterruptedException e){
            
        }
    }
    public void search(File file) throws IOException{
        try(Scanner in =new Scanner(file)){
            int lineNumber=0;
            while(in.hasNextLine()){
                lineNumber++;
                String line=in.nextLine();
                if(line.contains(keyword)){
                    System.out.printf("%s:%d:%s%n",file.getPath(),lineNumber,line);
                }
            }
        }
    }
}
View Code

 

ForkJoinTest

技术分享
package corejava;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final int SIZE =10000000;
        double[] numbers=new double[SIZE];
        for(int i=0;i<SIZE;i++){
            numbers[i]=Math.random();
        }
        Counter counter=new Counter(numbers,0,numbers.length,
                    new Filter(){
                        public boolean accept(double x){
                            return x>0.5;
                        }
                    });
        ForkJoinPool pool=new ForkJoinPool();
        pool.invoke(counter);
        System.out.println(counter.join());
    }
}
interface Filter{
    boolean accept(double t);
}
class Counter extends RecursiveTask<Integer>{
    public static final int THRESHOLD=1000;
    private double[] values;
    private int from;
    private int to;
    private Filter filter;
    public Counter(double[]values,int from,int to,Filter filter){
        this.values=values;
        this.from=from;
        this.to=to;
        this.filter=filter;
    }
    protected Integer compute(){
        if(to-from<THRESHOLD){
            int count =0;
            for(int i=from;i<to;i++){
                if(filter.accept(values[i])){
                    count++;
                }
            }
            return count;
        }else{
            int mid =(from+to)/2;
            Counter first = new Counter(values,from,mid,filter);
            Counter second = new Counter(values,mid,to,filter);
            invokeAll(first,second);
            return first.join()+second.join();
        }
    }
}
View Code

 

输出:

5001345

 

core java

标签:

原文地址:http://www.cnblogs.com/yuanzhenliu/p/5799670.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!