初尝Java异步编程

最近从头了解了一下java的异步编程,通过一些例子去展现不同java版本下怎么去实现任务的并行。 

(一)Java 1.0的通过Thread 类 和 Runnable接口

Thread类实现了Runnable接口。

一般用法:

1)创建一个类SendToCUPD,实现Runnable接口,重写run()方法去实现任务

2)创建一个类SendToCUPD的实例, 作为参数去新建一个Thread并调用Thread.start 方法。 然后系统去新建一个线程去执行这个任务

public class JThread {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println("get request from TC thread id="+Thread.currentThread().getId());	
		Runnable createRM = new CreateRichMedia("Thread RM");
		new Thread(createRM).start();
		
		Runnable tCUPD=new SendToCUPD("Thread CUPD");
		new Thread(tCUPD).start();
		System.out.println("End main method");	
		
		
	}

}

class SendToCUPD implements Runnable{
	public String TName;
	public SendToCUPD(String TName) {
		// TODO Auto-generated constructor stub
		this.TName=TName;
	}

	@Override
	public void run() {
		System.out.println("b4 send to cupd");
		try {
			System.out.println(" sending to cupd, thread id="+Thread.currentThread().getId());
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("end send to cupd");
	}
	
}

class CreateRichMedia implements Runnable{

	public String TName;
	public CreateRichMedia(String TName) {
		// TODO Auto-generated constructor stub
		this.TName=TName;
	}

	@Override
	public void run() {

		System.out.println("start response Rich media");
		try {
			System.out.println("creating response Rich media, thread id="+Thread.currentThread().getId());
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("End response Rich media");
	
		
	}
	
}


(二)Java5, Callable, Future, FutureTask

通过Runable和Thread, 无法获取子线程的运行结果。 
Java5 引入了 java.util.concurrent, 可以获取到子线程的运行结果。 

Future接口可以理解成一个任务, Future.get()方法可以获取任务的运行结果

例子步骤:

1)创建一个RMTask和CUPDTask, 实现Callable接口。 重写call()方法去实现任务

2)通过Executors类去创建一个线程池

3)通过Executors.submit()去创建子线程去执行任务。

public class J5Thread {

	public static void main(String[] args) {
		// ES
		System.out.println("Get request from TC, thread id="+Thread.currentThread().getId());
		ExecutorService ES=Executors.newCachedThreadPool();
		
		//task
		Callable<Integer> rmTask= new RMTask();
		Callable<Integer> cupdTask = new CUPDTask();
		
		//ES submit task, 
		//param is callable
		//return result
		Future<Integer> rmResult=ES.submit(rmTask);
		Future<Integer> cupdResult= ES.submit(cupdTask);
		ES.shutdown();
		
		System.out.println("ES shutdown, thread id="+Thread.currentThread().getId());
		//ES shutdown
		
		try {
			Integer result = rmResult.get();
			System.out.println("process rmResult, thread id="+Thread.currentThread().getId());
			System.out.println("process rmResult="+result);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}
}
//define task
class RMTask implements Callable<Integer>{

	@Override
	public Integer call() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("creating response Rich media, thread id="+Thread.currentThread().getId());
		Thread.sleep(3000);
		System.out.println("end response Rich media, thread id="+Thread.currentThread().getId());
		return new Integer(3);
	}
	
}

class CUPDTask implements Callable<Integer>{

	@Override
	public Integer call() throws Exception {
		System.out.println("creating CUPD msg, thread id="+Thread.currentThread().getId());
		Thread.sleep(8000);
		System.out.println("end response Rich media, thread id="+Thread.currentThread().getId());
		return new Integer(10);
	}
	


(三)Java7, fork/join

Java 7在java.util.concurrent包下加入了支持fork/join框架的RecursiveTask,forkjoinpool 

例子,去计算从start到end的连续数字的和:

1)执行任务的类要继承RecursiveTask类

2)定义一个compute方法,将要算的数分成两组,再分别调用compute方法去算。 运用了递归算法 

3)定义一个ForkJoinPool去执行任务, submit方法返还一个Future类, 通过future.get()去获取任务结果

public class J7ForkJoin extends RecursiveTask<Integer>{
	private static final int THRESHOLD=5;
	private int beginning;
	private int ending;
	
	public J7ForkJoin(int beginning, int ending) {
		super();
		this.beginning = beginning;
		this.ending = ending;
	}

	//override compute
	@Override
	protected Integer compute() {
		// TODO Auto-generated method stub
		//check if still need fork
		int sum=0;
		boolean canCompute = (ending-beginning)<=THRESHOLD;
		if(canCompute){
			//no need
			System.out.println("no need fork, ThreadID="+Thread.currentThread().getId());
			System.out.println("no need fork, beginning="+this.beginning);
			System.out.println("no need fork, ending="+this.ending);
			for(int i=beginning; i<=ending;++i){
				sum+=i;
			}
			return sum;
		}else{
			//need
			int interim=(this.ending+this.beginning)/2;
			//5+1 /2 =3 1-3
			//6+1 /2 =3 1-3
			System.out.println("need fork, ThreadID="+Thread.currentThread().getId());
			System.out.println("need fork, interim="+interim);
			J7ForkJoin leftTask=new J7ForkJoin(this.beginning , interim);
			J7ForkJoin rightTask=new J7ForkJoin(interim+1, this.ending);
			//.fork
			leftTask.fork();
			rightTask.fork();
			
			//get reuslt
			int leftResult=leftTask.join();
			int rightResult=rightTask.join();
			sum =leftResult+rightResult;
			return sum;
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ForkJoinPool FJPool=new ForkJoinPool();
		J7ForkJoin task=new J7ForkJoin(1, 20);
		Future<Integer> result=FJPool.submit(task);
		try {
			System.out.println("main result="+result.get());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

Java8 CompletableFuture

可以定义回调函数, 子线程执行完后,会触发回调函数

步骤:

1)CompletableFuture.supplyAsync(),定义要执行的异步任务

2)cupdResult.thenAccept(new Consumer<String>() , 重写accept()方法去定义回调函数

public class J8ComFuture3 {

	public static void main(String[] args) {

		ExecutorService executor = Executors.newFixedThreadPool(10);
		// get msg from tc
		System.out.println("Got reqeust from TC");

		// prepare RM
		System.out.println("prepare RM msg");

		// trigger cupd
		CompletableFuture<String> cupdResult = CompletableFuture.supplyAsync(new Supplier<String>() {

			@Override
			public String get() {
				// TODO Auto-generated method stub
				try {
					System.out.println("sleep b4");
					TimeUnit.SECONDS.sleep(1);
					System.out.println("sleep after");
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "msg from CUPD";
			}
		}, executor);

		// return cupd
		cupdResult.thenAccept(new Consumer<String>() {

			// callback method
			public void accept(String arg0) {
				System.out.println("return msg to TC=" + arg0);

			}

		});

		// return RM
		System.out.println("return RM msg to customer");

	}

}








  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Title: Python Hacking Essentials Author: Earnest Wish Length: 214 pages Edition: 1 Language: English Publisher: CreateSpace Independent Publishing Platform Publication Date: 2015-04-01 ISBN-10: 1511797568 ISBN-13: 9781511797566 Target Audience This book is not for professional hackers. Instead, this book is made for beginners who have programming experience and are interested in hacking. Here, hacking techniques that can be easily understood have been described. If you only have a home PC, you can test all the examples provided here. I have included many figures that are intuitively understandable rather than a litany of explanations. Therefore, it is possible to gain some practical experience while hacking, since I have only used examples that can actually be implemented. This book is therefore necessary for ordinary people who have a curiosity of hackers and are interested in computers. Organization of the Book This book is made up of five major parts, from basic knowledge to actual hacking code. A beginner is naturally expected to become a hacker while reading this book. Hacking Preparation: Briefly introduce the basic Python syntax that is necessary for hacking. Application Hacking: Introduce the basic skills to hack an application, such as Keyboard hooking, API hooking and image file hacking. Web Hacking: The Virtual Box test environment configuration is used for a Web Shell attack to introduce web hacking, which is currently an important issue. The techniques include SQL Injection, Password Cracking, and a Web Shell Attack. Network Hacking: A variety of tools and the Python language can be combined to support network hacking and to introduce the network hacking technique. Briefly, we introduce NMap with the Wireshark tool, and hacking techniques such as Port Scanning, Packet Sniffing, TCP SYN Flood, Slowris Attack are introduced. System Hacking:System hacking is difficult to understand for beginners, and in this section, figures are used to introduce difficult concepts. The hacking techniques that are introduced include a Backdoor, Registry Handling, Stack Based Buffer Overflow, and SEH Based Buffer Overflow. While reading this book, it is possible to obtain answers for such problems one by one. After reading the last chapter, you will gain the confidence to be a hacker. Features of this book When you start to study hacking, the most difficult task is to configure the test environment. There are many problems that need to be addressed, such as choosing from the variety in operating systems, obtaining expensive equipment and using complex technology. Such problems are too difficult to take in at once, so this book overcomes this difficulty by implementing a simple idea. First, systems will be described as Windows-based We are very familiar with Windows, so it is very easy to understand a description based on Windows. Since Windows, Linux, Unix, and Android are all operating systems, it is possible to expand the concepts that are discussed here. Second, we use a virtual machine called Virtual Box For hacking, it is necessary to connect at least three or more computers on a network. Since it is a significant investment to buy a few computers only to study these techniques, a virtual machine can be used instead to easily implement a honeypot necessary to hack by creating multiple virtual machines on a single PC. Finally, abstract concepts are explained using figures Rather than simply using words for descriptions, graphics are very effective in transferring information. An abstract concept can materialize through the use of graphics in order to improve the understanding on the part of the reader. Table of Contents Chapter 1 Preparation for Hacking Chapter 2 Application Hacking Chapter 3 Web Hacking Chapter 4 Network Hacking Chapter 5 System Hacking Chapter 6 Conclusion

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值