导航:首页 > 编程语言 > java异步读表

java异步读表

发布时间:2025-02-16 11:06:37

❶ 如何在java中获取线程异步执行之后的结果

java中提供了Future<V>接口和实现了Future接口的FutureTask<V> 类来将线程执行之后的结果返回(通过get()方法)。
1.Future<V>接口
Runnable接口执行任务是不返回任何值的,Runnable的run()方法的执行结果是void,而Future接口的call方法是有返回结果的,这是Runnable跟Future的区别之一,它们的另一个不同之处就是实现了Runnable接口的任务执行是调用ExecutorService的execute(Runnable task)方法,而实现了Future接口的任务是调用ExecutorService的submit(Future task)方法。调用Future的get()方法就能直接得到任务的返回值,该方法会一直阻塞直到任务的结果出来为止,我们可以调用Future的isDone()方法来判断该任务的结果是否准备就绪。
[java] view plain
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newCachedThreadPool();
Future result1 = executor.submit(new Callable() {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += i;
}
return sum;
}
});
Future result2 = executor.submit(new Callable() {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 10; i < 100; i++) {
sum += i;
}
return sum;
}
});
executor.shutdown();
System.out.println(result1.get() + result2.get());
}
}
2.FutureTask类
FutureTask实现了Future接口,将一个Callable实例作为参数传给它,就能创建一个FutureTask实例,然后用ExecutorService的submit方法来执行这个实例。最后同样是用get方法获取线程执行后的结果。
[plain] view plain
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
public class TestFutureTask {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newCachedThreadPool();
Callable task = new Callable() {
@Override
public String call() throws Exception {
return "结果";
}
};
FutureTask ft = new FutureTask(task);
executor.submit(ft);
System.out.println(ft.get());
executor.shutdown();
}
}empty

❷ java 异步编程

用异步输入输出流编写Socket进程通信程序
在Merlin中加入了用于实现异步输入输出机制的应用程序接口包:java.nio(新的输入输出包,定义了很多基本类型缓冲(Buffer)),java.nio.channels(通道及选择器等,用于异步输入输出),java.nio.charset(字符的编码解码)。通道(Channel)首先在选择器(Selector)中注册自己感兴趣的事件,当相应的事件发生时,选择器便通过选择键(SelectionKey)通知已注册的通道。然后通道将需要处理的信息,通过缓冲(Buffer)打包,编码/解码,完成输入输出控制。

通道介绍:
这里主要介绍ServerSocketChannel和 SocketChannel.它们都是可选择的(selectable)通道,分别可以工作在同步和异步两种方式下(注意,这里的可选择不是指可以选择两种工作方式,而是指可以有选择的注册自己感兴趣的事件)。可以用channel.configureBlocking(Boolean )来设置其工作方式。与以前版本的API相比较,ServerSocketChannel就相当于ServerSocket(ServerSocketChannel封装了ServerSocket),而SocketChannel就相当于Socket(SocketChannel封装了Socket)。当通道工作在同步方式时,编程方法与以前的基本相似,这里主要介绍异步工作方式。

所谓异步输入输出机制,是指在进行输入输出处理时,不必等到输入输出处理完毕才返回。所以异步的同义语是非阻塞(None Blocking)。在服务器端,ServerSocketChannel通过静态函数open()返回一个实例serverChl。然后该通道调用serverChl.socket().bind()绑定到服务器某端口,并调用register(Selector sel, SelectionKey.OP_ACCEPT)注册OP_ACCEPT事件到一个选择器中(ServerSocketChannel只可以注册OP_ACCEPT事件)。当有客户请求连接时,选择器就会通知该通道有客户连接请求,就可以进行相应的输入输出控制了;在客户端,clientChl实例注册自己感兴趣的事件后(可以是OP_CONNECT,OP_READ,OP_WRITE的组合),调用clientChl.connect(InetSocketAddress )连接服务器然后进行相应处理。注意,这里的连接是异步的,即会立即返回而继续执行后面的代码

选择器和选择键介绍:
选择器(Selector)的作用是:将通道感兴趣的事件放入队列中,而不是马上提交给应用程序,等已注册的通道自己来请求处理这些事件。换句话说,就是选择器将会随时报告已经准备好了的通道,而且是按照先进先出的顺序。那么,选择器是通过什么来报告的呢?选择键(SelectionKey)。选择键的作用就是表明哪个通道已经做好了准备,准备干什么。你也许马上会想到,那一定是已注册的通道感兴趣的事件。不错,例如对于服务器端serverChl来说,可以调用key.isAcceptable()来通知serverChl有客户端连接请求。相应的函数还有:SelectionKey.isReadable(),SelectionKey.isWritable()。一般的,在一个循环中轮询感兴趣的事件(具体可参照下面的代码)。如果选择器中尚无通道已注册事件发生,调用Selector.select()将阻塞,直到有事件发生为止。另外,可以调用selectNow()或者select(long timeout)。前者立即返回,没有事件时返回0值;后者等待timeout时间后返回。一个选择器最多可以同时被63个通道一起注册使用。
应用实例:
下面是用异步输入输出机制实现的客户/服务器实例程序――程序清单1(限于篇幅,只给出了服务器端实现,读者可以参照着实现客户端代码):

程序类图

public class NBlockingServer {
int port = 8000;
int BUFFERSIZE = 1024;
Selector selector = null;
ServerSocketChannel serverChannel = null;
HashMap clientChannelMap = null;//用来存放每一个客户连接对应的套接字和通道

public NBlockingServer( int port ) {
this.clientChannelMap = new HashMap();
this.port = port;
}

public void initialize() throws IOException {
//初始化,分别实例化一个选择器,一个服务器端可选择通道
this.selector = Selector.open();
this.serverChannel = ServerSocketChannel.open();
this.serverChannel.configureBlocking(false);
InetAddress localhost = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(localhost, this.port );
this.serverChannel.socket().bind(isa);//将该套接字绑定到服务器某一可用端口
}
//结束时释放资源
public void finalize() throws IOException {
this.serverChannel.close();
this.selector.close();
}
//将读入字节缓冲的信息解码
public String decode( ByteBuffer byteBuffer ) throws
CharacterCodingException {
Charset charset = Charset.forName( "ISO-8859-1" );
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode( byteBuffer );
String result = charBuffer.toString();
return result;
}
//监听端口,当通道准备好时进行相应操作
public void portListening() throws IOException, InterruptedException {
//服务器端通道注册OP_ACCEPT事件
SelectionKey acceptKey =this.serverChannel.register( this.selector,
SelectionKey.OP_ACCEPT );
//当有已注册的事件发生时,select()返回值将大于0
while (acceptKey.selector().select() > 0 ) {
System.out.println("event happened");
//取得所有已经准备好的所有选择键
Set readyKeys = this.selector.selectedKeys();
//使用迭代器对选择键进行轮询
Iterator i = readyKeys.iterator();
while (i
else if ( key.isReadable() ) {//如果是通道读准备好事件
System.out.println("Readable");
//取得选择键对应的通道和套接字
SelectableChannel nextReady =
(SelectableChannel) key.channel();
Socket socket = (Socket) key.attachment();
//处理该事件,处理方法已封装在类ClientChInstance中
this.readFromChannel( socket.getChannel(),
(ClientChInstance)
this.clientChannelMap.get( socket ) );
}
else if ( key.isWritable() ) {//如果是通道写准备好事件
System.out.println("writeable");
//取得套接字后处理,方法同上
Socket socket = (Socket) key.attachment();
SocketChannel channel = (SocketChannel)
socket.getChannel();
this.writeToChannel( channel,"This is from server!");
}
}
}
}
//对通道的写操作
public void writeToChannel( SocketChannel channel, String message )
throws IOException {
ByteBuffer buf = ByteBuffer.wrap( message.getBytes() );
int nbytes = channel.write( buf );
}
//对通道的读操作
public void readFromChannel( SocketChannel channel, ClientChInstance clientInstance )
throws IOException, InterruptedException {
ByteBuffer byteBuffer = ByteBuffer.allocate( BUFFERSIZE );
int nbytes = channel.read( byteBuffer );
byteBuffer.flip();
String result = this.decode( byteBuffer );
//当客户端发出”@exit”退出命令时,关闭其通道
if ( result.indexOf( "@exit" ) >= 0 ) {
channel.close();
}
else {
clientInstance.append( result.toString() );
//读入一行完毕,执行相应操作
if ( result.indexOf( "\n" ) >= 0 ){
System.out.println("client input"+result);
clientInstance.execute();
}
}
}
//该类封装了怎样对客户端的通道进行操作,具体实现可以通过重载execute()方法
public class ClientChInstance {
SocketChannel channel;
StringBuffer buffer=new StringBuffer();
public ClientChInstance( SocketChannel channel ) {
this.channel = channel;
}
public void execute() throws IOException {
String message = "This is response after reading from channel!";
writeToChannel( this.channel, message );
buffer = new StringBuffer();
}
//当一行没有结束时,将当前字窜置于缓冲尾
public void append( String values ) {
buffer.append( values );
}
}

//主程序
public static void main( String[] args ) {
NBlockingServer nbServer = new NBlockingServer(8000);
try {
nbServer.initialize();
} catch ( Exception e ) {
e.printStackTrace();
System.exit( -1 );
}
try {
nbServer.portListening();
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}

程序清单1

小结:
从以上程序段可以看出,服务器端没有引入多余线程就完成了多客户的客户/服务器模式。该程序中使用了回调模式(CALLBACK)。需要注意的是,请不要将原来的输入输出包与新加入的输入输出包混用,因为出于一些原因的考虑,这两个包并不兼容。即使用通道时请使用缓冲完成输入输出控制。该程序在Windows2000,J2SE1.4下,用telnet测试成功。

❸ java中异步处理和同步处理分别是什么意思

同步:发送一个请求,等待返回,然后再发送下一个请求
异步:发送一个请求,不等待返回,随时可以再发送下一个请求

同步可以避免出现死锁,读脏数据的发生,一般共享某一资源的时候用,如果每个人都有修改权限,同时修改一个文件,有可能使一个人读取另一个人已经删除的内容,就会出错,同步就会按顺序来修改。
异步则是可以提高效率了,现在cpu都是双核,四核,异步处理的话可以同时做多项工作,当然必须保证是可以并发处理的。
这些都是对的。
同步和异步最大的区别就在于。一个需要等待,一个不需要等待。
比如广播,就是一个异步例子。发起者不关心接收者的状态。不需要等待接收者的返回信息
电话,就是一个同步例子。发起者需要等待接收者,接通电话后,通信才开始。需要等待接收者的返回信息

❹ java队列实现异步执行

在整个思路上要调整一下

1、会有很多线程给一个队列上添加任务

2、有一个或者多个线程逐个执行队列的任务


考虑一下几点:

1、没有任务时,队列执行线程处于等待状态

2、添加任务时,激活队列执行线程,全部run起来,首先抢到任务的执行,其他全部wait


给个小例子吧

packageorg;
importjava.util.LinkedList;
importjava.util.List;
publicclassQueues{
publicstaticList<Task>queue=newLinkedList<Task>();
/**
*假如参数o为任务
*@paramo
*/
publicstaticvoidadd(Taskt){
synchronized(Queues.queue){
Queues.queue.add(t);//添加任务
Queues.queue.notifyAll();//激活该队列对应的执行线程,全部Run起来
}
}
staticclassTask{
publicvoidtest(){
System.out.println("我被执行了");
}
}
}
packageorg;
importjava.util.List;
{
@Override
publicvoidrun(){
while(true){
synchronized(Queues.queue){
while(Queues.queue.isEmpty()){//
try{
Queues.queue.wait();//队列为空时,使线程处于等待状态
}catch(InterruptedExceptione){
e.printStackTrace();
}
System.out.println("wait...");
}
Queues.Taskt=Queues.queue.remove(0);//得到第一个
t.test();//执行该任务
System.out.println("end");
}
}
}
publicstaticvoidmain(String[]args){
Exece=newExec();
for(inti=0;i<2;i++){
newThread(e).start();//开始执行时,队列为空,处于等待状态
}
//上面开启两个线程执行队列中的任务,那就是先到先得了
//添加一个任务测试
Queues.Taskt=newQueues.Task();
Queues.add(t);//执行该方法,激活所有对应队列,那两个线程就会开始执行啦
}

}


上面的就是很简单的例子了

阅读全文

与java异步读表相关的资料

热点内容
typecho教程 浏览:662
qq申诉英文网站如何修改代码 浏览:757
iphone4s8g升级ios9 浏览:177
js怎么设置打印横向边距 浏览:726
慧编程里的画笔用不了怎么办 浏览:19
第七次人口普查数据哪里看 浏览:126
plc编程mon是怎么缩小 浏览:633
北大青鸟网络主要课程 浏览:63
ug编程t形槽怎么做 浏览:283
技术性文件的分类有哪些 浏览:98
iphone文件到电脑 浏览:647
证券pdf文件的电子录入 浏览:214
htmlform上传文件 浏览:715
电脑中毒了每个文件夹多出图片 浏览:228
苍南如何制作一个营销网站 浏览:933
刻录进光盘的文件缓存在哪里 浏览:94
开发影视网站怎么取得影视资源 浏览:565
平安wifi登录网络异常 浏览:638
u盘病毒清除文件会不会消失 浏览:126
数独游戏下载安卓 浏览:734

友情链接