導航:首頁 > 編程語言 > 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非同步讀表相關的資料

熱點內容
win10怎樣改變指針 瀏覽:653
電視可以下載怎麼樣的象棋app 瀏覽:60
什麼app能看雜志 瀏覽:803
文件夾字體變成藍色 瀏覽:398
如何注冊房產網路賬號 瀏覽:20
cmd為後綴的文件夾 瀏覽:484
手機越用網路越差是什麼原因 瀏覽:983
蘋果手機怎麼創建一個txt文件 瀏覽:682
ipad看swf文件 瀏覽:932
VB的編程規則有哪些 瀏覽:771
總是發簡訊少兒編程是什麼東西 瀏覽:863
java正則表達式匹配手機號碼 瀏覽:201
javapaging 瀏覽:946
java邏輯 瀏覽:360
程序員用哪個軟體編程序 瀏覽:768
win10字體庫文件夾是只讀 瀏覽:329
u盤拔出文件丟失 瀏覽:75
怎麼在手機上刪除qq群文件在哪裡 瀏覽:638
qq討論組下載文件記錄 瀏覽:164
源代碼種子 瀏覽:935

友情鏈接