天天看點

Java協程架構Quasar Demo (maven)

主線程随機抽一個10以内的整數,然後送入整數管道,死循環,且每次循環後休眠若幹ms

建立一個Fiber協程,死循環從整數管道裡讀取,如果讀取到的數字不為空則列印出來

  • maven依賴
    <!--        協程Quasar-->
    <dependency>
        <groupId>co.paralleluniverse</groupId>
        <artifactId>quasar-core</artifactId>
        <version>0.7.10</version>
        <classifier>jdk8</classifier>
    </dependency>
          
  • 測試代碼
    import co.paralleluniverse.fibers.Fiber;
    import co.paralleluniverse.fibers.SuspendExecution;
    import co.paralleluniverse.strands.SuspendableRunnable;
    import co.paralleluniverse.strands.channels.Channels;
    import co.paralleluniverse.strands.channels.IntChannel;
    
    import java.io.IOException;
    import java.util.Random;
    import java.util.concurrent.ExecutionException;
    
    public class QuasarTest {
        static void doAll2(){
            final IntChannel increasingToEcho = Channels.newIntChannel(10);
    
            new Fiber<Void>(new SuspendableRunnable() {
                @Override
                public void run() throws SuspendExecution, InterruptedException {
                    while (true){
                        Integer integer=increasingToEcho.receive();
                        if(integer!=null&&integer!=0){
                            System.out.println(String.format("get %s",integer));
                        }else{
      					  System.out.println("空的");
      					}
                    }
                }
            }).start();
    
            test(increasingToEcho);
    
            while (true){
    
            }
        }
    
        static void test(IntChannel c){
            try {
                Random random=new Random();
    
                while (true){
                    int t=random.nextInt(10)+1;
                    c.send(t);
                    Thread.sleep(200*t);
                }
            } catch (SuspendExecution suspendExecution) {
                suspendExecution.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        static public void main(String[] args) throws ExecutionException, InterruptedException, SuspendExecution, IOException {
            doAll2();
        }
    }
    
          
  • 找到自己maven包路徑
    • 點進Fiber類,然後向上級找一隻找到那個maven依賴quasar-core-0.7.10-jdk8.jar
    • 然後複制路徑 copy path得到
      C:\Users\lenovo\.m2\repository\co\paralleluniverse\quasar-core\0.7.10\quasar-core-0.7.10-jdk8.jar
            
    • 把路徑加入到運作參數
      -javaagent:C:\Users\lenovo\.m2\repository\co\paralleluniverse\quasar-core\0.7.10\quasar-core-0.7.10-jdk8.jar
            

繼續閱讀