Java併發核心-exchanger

Exchanger類的做用

Exchanger的功能能夠使兩個線程(重點: 只有兩個線程)之間傳輸數據

  • 重點是exchange()方法java

  • exchange()方法是阻塞執行的,能夠設置超時時間 可調用不一樣的Apiide

    package com.f.fmodules.fuser.example.exchanger;
    
    	import java.util.concurrent.Exchanger;
    
    	public class ExchangerThread extends Thread{
    
    		private Exchanger<String> exchanger;
    		private String threadName;
    		private String changeString;
    
    
    		ExchangerThread(String threadName, String changeString, Exchanger<String> exchanger) {
    			super();
    			this.threadName = threadName;
    			this.changeString = changeString;
    			this.exchanger = exchanger;
    		}
    
    		@Override
    		public void run() {
    			try {
    				System.out.println("Thread[" + threadName + "]交換到消息:" + exchanger.exchange(changeString));
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    
    	}
    package com.f.fmodules.fuser.example.exchanger;
    
    	import java.util.concurrent.Exchanger;
    
    	public class ExchangerTest {
    
    		public static void main(String[] args) {
    			Exchanger<String> exchanger = new Exchanger<>();
    			ExchangerThread t1 = new ExchangerThread("1","changString1", exchanger);
    			ExchangerThread t2 = new ExchangerThread("2","changString2", exchanger);
    			t1.start();
    			t2.start();
    		}
    
    	}
  • 運行結果
    this

  • 例: 三個線程操做線程

    package com.f.fmodules.fuser.example.exchanger;
    
    	import java.util.concurrent.Exchanger;
    
    	public class ExchangerTest {
    
    		public static void main(String[] args) {
    			Exchanger<String> exchanger = new Exchanger<>();
    			ExchangerThread t1 = new ExchangerThread("1","changString1", exchanger);
    			ExchangerThread t2 = new ExchangerThread("2","changString2", exchanger);
    			ExchangerThread t3 = new ExchangerThread("3","changString3", exchanger);
    			t1.start();
    			t2.start();
    			t3.start();
    		}
    
    	}
  • 此時程序的運行結果是不肯定的,屢次運行能夠發現,配對結果多是Thread[2]和Thread[3]交換,也多是Thread[1]和Thread[2]交換,而剩下的未獲得配對的線程,則會被阻塞,永久等待,直到與之配對的線程到達位置,對於本程序,則只能強制將其中止code

  • 阻塞狀態
    blog

  • 可設置五秒超時時間it

    System.out.println("Thread[" + threadName + "]交換到消息:" + exchanger.exchange(changeString, 5, TimeUnit.SECONDS));
  • 運行結果io

相關文章
相關標籤/搜索