public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    for (int i = 0; i < 5; i++) exec.execute(new Task());
    exec.execute(new Task2());
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(
        new TimerTask() {
          boolean prod = true;

          public void run() {
            if (prod) {
              System.out.print("\nnotify() ");
              Task.blocker.prod();
              prod = false;
            } else {
              System.out.print("\nnotifyAll() ");
              Task.blocker.prodAll();
              prod = true;
            }
          }
        },
        400,
        400); // Run every .4 second
    TimeUnit.SECONDS.sleep(5); // Run for a while...
    timer.cancel();
    System.out.println("\nTimer canceled");
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.print("Task2.blocker.prodAll() ");
    Task2.blocker.prodAll();
    TimeUnit.MILLISECONDS.sleep(500);
    System.out.println("\nShutting down");
    exec.shutdownNow(); // Interrupt all tasks
  }
 public static void main(String[] args) throws Exception {
   Car car = new Car();
   ExecutorService exec = Executors.newCachedThreadPool();
   exec.execute(new WaxOff(car));
   exec.execute(new WaxOn(car));
   TimeUnit.SECONDS.sleep(5); // Run for a while...
   exec.shutdownNow(); // Interrupt all tasks
 }
  public static void main(String[] args) {
    // Create a thread pool with two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);

    System.out.println("Thread 1\t\tThread 2\t\tBalance");

    executor.execute(new DepositTask());
    executor.execute(new WithDrawTask());
    executor.shutdown();
  }
 public static void main(String[] args) throws Exception {
   ToastQueue dryQueue = new ToastQueue(),
       butteredQueue = new ToastQueue(),
       finishedQueue = new ToastQueue();
   ExecutorService exec = Executors.newCachedThreadPool();
   exec.execute(new Toaster(dryQueue));
   exec.execute(new Butterer(dryQueue, butteredQueue));
   exec.execute(new Jammer(butteredQueue, finishedQueue));
   exec.execute(new Eater(finishedQueue));
   TimeUnit.SECONDS.sleep(5);
   exec.shutdownNow();
 }
 public static void main(String[] args) throws Exception {
   if (args.length > 0) size = new Integer(args[0]);
   if (args.length > 1) delay = new Integer(args[1]);
   ExecutorService exec = Executors.newCachedThreadPool();
   Exchanger<List<Fat>> xc = new Exchanger<List<Fat>>();
   List<Fat> producerList = new CopyOnWriteArrayList<Fat>(),
       consumerList = new CopyOnWriteArrayList<Fat>();
   exec.execute(new ExchangerProducer<Fat>(xc, BasicGenerator.create(Fat.class), producerList));
   exec.execute(new ExchangerConsumer<Fat>(xc, consumerList));
   TimeUnit.SECONDS.sleep(delay);
   exec.shutdownNow();
 }
 public Restaurant(ExecutorService e, int nWaitPersons, int nChefs) {
   exec = e;
   for (int i = 0; i < nWaitPersons; i++) {
     WaitPerson waitPerson = new WaitPerson(this);
     waitPersons.add(waitPerson);
     exec.execute(waitPerson);
   }
   for (int i = 0; i < nChefs; i++) {
     Chef chef = new Chef(this);
     chefs.add(chef);
     exec.execute(chef);
   }
 }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   // If line is too long, customers will leave:
   CustomerLine customers = new CustomerLine(MAX_LINE_SIZE);
   exec.execute(new CustomerGenerator(customers));
   // Manager will add and remove tellers as necessary:
   exec.execute(new TellerManager(exec, customers, ADJUSTMENT_PERIOD));
   if (args.length > 0) // Optional argument
   TimeUnit.SECONDS.sleep(new Integer(args[0]));
   else {
     System.out.println("Press ‘Enter’ to quit");
     System.in.read();
   }
   exec.shutdownNow();
 }
  public HorseRace(int nHorses, final int pause) {

    /**
     * 可以想CyclicBarrier提供一个"栅栏动作",他是一个Runnable,当计数值达到
     * 0时候自动执行--这是CyclicBarrier和CountDownLatch之间的另一个区别,这 里,栅栏动作作为匿名内部类创建的,它被提交给了CyclicBarrier的构造器
     */
    barrier =
        new CyclicBarrier(
            nHorses,
            new Runnable() {
              public void run() {
                StringBuilder s = new StringBuilder();
                for (int i = 0; i < FINISH_LINE; i++) s.append("="); // The fence on the racetrack
                print(s);
                for (Horse horse : horses) print(horse.tracks());
                for (Horse horse : horses)
                  if (horse.getStrides() >= FINISH_LINE) {
                    print(horse + "won!");
                    exec.shutdownNow();
                    return;
                  }
                try {
                  TimeUnit.MILLISECONDS.sleep(pause);
                } catch (InterruptedException e) {
                  print("barrier-action sleep interrupted");
                }
              }
            });
    for (int i = 0; i < nHorses; i++) {
      Horse horse = new Horse(barrier);
      horses.add(horse);
      exec.execute(horse);
    }
  }
 public void adjustTellerNumber() {
   // This is actually a control system. By adjusting
   // the numbers, you can reveal stability issues in
   // the control mechanism.
   // If line is too long, add another teller:
   if (customers.size() / workingTellers.size() > 2) {
     // If tellers are on break or doing
     // another job, bring one back:
     if (tellersDoingOtherThings.size() > 0) {
       Teller teller = tellersDoingOtherThings.remove();
       teller.serveCustomerLine();
       workingTellers.offer(teller);
       return;
     }
     // Else create (hire) a new teller
     Teller teller = new Teller(customers);
     exec.execute(teller);
     workingTellers.add(teller);
     return;
   }
   // If line is short enough, remove a teller:
   if (workingTellers.size() > 1 && customers.size() / workingTellers.size() < 2)
     reassignOneTeller();
   // If there is no line, we only need one teller:
   if (customers.size() == 0) while (workingTellers.size() > 1) reassignOneTeller();
 }
 /**
  * 将任务投入线程池执行
  *
  * @param worker
  * @return
  */
 public <T> FutureTask<T> execute(final Worker<T> worker) {
   Callable<T> call =
       new Callable<T>() {
         @Override
         public T call() throws Exception {
           return postResult(worker, worker.doInBackground());
         }
       };
   FutureTask<T> task =
       new FutureTask<T>(call) {
         @Override
         protected void done() {
           try {
             get();
           } catch (InterruptedException e) {
             Log.e(TAG, e);
             worker.abort();
             postCancel(worker);
             e.printStackTrace();
           } catch (ExecutionException e) {
             Log.e(TAG, e.getMessage());
             e.printStackTrace();
             throw new RuntimeException(
                 "An error occured while executing doInBackground()", e.getCause());
           } catch (CancellationException e) {
             worker.abort();
             postCancel(worker);
             Log.e(TAG, e);
             e.printStackTrace();
           }
         }
       };
   threadPool.execute(task);
   return task;
 }
 /**
  * Executes the specified runnable on the worker thread of the view. Execution is performed
  * sequentially in the same sequence as the runnables have been passed to this method.
  */
 @Override
 public void execute(Runnable worker) {
   if (executor == null) {
     executor = Executors.newSingleThreadExecutor();
   }
   executor.execute(worker);
 }
  /**
   * Submits a value-returning task for execution and returns a Future representing the pending
   * results of the task. Upon completion, this task may be taken or polled.
   *
   * @param task the task to submit
   * @return a future to watch the task
   */
  public <V> Future<V> submit(Callable<V> task) {
    Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");

    InternalFutureTask<V> futureTask = new InternalFutureTask<V>(new FutureTask<V>(task));
    executorService.execute(futureTask);
    return futureTask;
  }
  /** {@inheritDoc} */
  @Override
  protected void maybeStartStream() throws IOException {
    // connector
    final StreamConnector connector = getStreamConnector();

    if (connector == null) return;

    synchronized (this) {
      if (started) return;

      threadPool.execute(
          new Runnable() {
            @Override
            public void run() {
              try {
                Sctp.init();

                runOnDtlsTransport(connector);
              } catch (IOException e) {
                logger.error(e, e);
              } finally {
                try {
                  Sctp.finish();
                } catch (IOException e) {
                  logger.error("Failed to shutdown SCTP stack", e);
                }
              }
            }
          });

      started = true;
    }
  }
 public void start() throws InterruptedException {
   barrier = new CyclicBarrier(numberOfCars, this);
   for (int i = 0; i < numberOfCars; i++) {
     pool.execute(new Car("Car" + i, 100 + random.nextInt(100), this));
   }
   pool.awaitTermination(300, TimeUnit.MILLISECONDS);
 }
 public static void test(IntGenerator go, int count) {
   System.out.println("Press Control-C to exit");
   ExecutorService exec = Executors.newCachedThreadPool();
   for (int i = 0; i < count; i++) {
     exec.execute(new EventChecker(go, i));
   }
   exec.shutdown();
 }
  /**
   * Submits a Runnable task for execution and returns a Future representing that task. Upon
   * completion, this task may be taken or polled.
   *
   * @param task the task to submit
   * @return a future to watch the task
   */
  public Future<?> submit(Runnable task) {
    Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");

    InternalFutureTask<Void> futureTask =
        new InternalFutureTask<Void>(new FutureTask<Void>(task, null));
    executorService.execute(futureTask);
    return futureTask;
  }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   for (int i = 0; i < N_ELEMENTS; i++)
     for (int j = 0; j < N_GENES; j++) GRID[i][j] = new AtomicInteger(rand.nextInt(1000));
   for (int i = 0; i < N_EVOLVERS; i++) exec.execute(new Evolver());
   TimeUnit.SECONDS.sleep(5);
   exec.shutdownNow();
 }
 /** Demonstrating the failing of the pre/post conditions of Even. */
 public static void main(String[] args) {
   ExecutorService e = Executors.newFixedThreadPool(10);
   Even ev = new Even();
   for (int i = 0; i < 10; i++) {
     e.execute(new EvenTask(ev));
   }
   e.shutdown();
 }
  @Override
  public Future<Boolean> connect(final String clientId) throws Exception {

    if (isConnected()) {
      throw new Exception("You are already connected");
    }

    // keep track of the original one, so we can detect change
    this.originalClientId = clientId;

    // this will help us do the connect synchronously
    connectLatch = new CountDownLatch(1);
    final Future connectFuture = connection.connect();

    FutureTask<Boolean> asdf =
        new FutureTask<Boolean>(
            new Callable<Boolean>() {

              @Override
              public Boolean call() {
                // TODO: notify callers somehow?

                try {
                  connectFuture.get(45, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                  e.printStackTrace();
                } catch (ExecutionException e) {
                  e.printStackTrace();
                } catch (TimeoutException e) {
                  e.printStackTrace();
                }

                if (connection.isConnected()) {
                  connection.send(new ConnectCommand(clientId));

                  // block while the signal server is thinking/hanging.
                  try {
                    connectLatch.await(45, TimeUnit.SECONDS);
                  } catch (InterruptedException e) {
                    e.printStackTrace();
                  }
                }

                final boolean result = isConnected();

                // queue it up, or else the "connect()" call will still block while the slow-ass
                // observers fire.
                connectEvent.notifyObservers(this, result);

                return result;
              }
            });

    // this background thread stops us from blocking.
    executor.execute(asdf);

    return asdf;
  }
Exemple #20
0
  public static void start() {
    if (started) return;

    // start code
    pool = Executors.newFixedThreadPool(poolSize);
    System.out.println("downloader start!!");
    for (DownloadTask task : tasks) pool.execute(task);
    started = true;
  }
  @Override
  public void execute(Runnable command) {
    if (command == null) {
      // TODO logger
      return;
    }

    executorService.execute(command);
  }
 public static void main(String[] args) {
   try {
     ExecutorService exec = Executors.newCachedThreadPool();
     exec.execute(new ExceptionThread());
   } catch (RuntimeException ue) {
     // This statement will NOT execute!
     System.out.println("Exception has been handled!");
   }
 }
 public TellerManager(ExecutorService e, CustomerLine customers, int adjustmentPeriod) {
   exec = e;
   this.customers = customers;
   this.adjustmentPeriod = adjustmentPeriod;
   // Start with a single teller:
   Teller teller = new Teller(customers);
   exec.execute(teller);
   workingTellers.add(teller);
 }
  /**
   * Testing threads thoroughly seems to be a lot of fun, I am not sure yet how to properly do that.
   * This test tests priority order and total sum received is equal to total sum sent. It also
   * simulates clients random hanging.
   */
  @Test
  public void testReceiveData() {

    DecorateCheckOrderAndCountSumMarshaller sumAppender =
        new DecorateCheckOrderAndCountSumMarshaller();
    QueueWorker worker = new QueueWorker(sumAppender);
    Thread workerThread = new Thread(worker);

    // run 20 clients, 10.000 items will be generated per client as defined in
    // src/test/properties/app.properties
    for (int i = 0; i < 20; i++) {
      Runnable clientHangSimulator = null;
      if (i % 5 == 0) {
        // simulate occasional client hang for four of the total twenty clients and check worker is
        // not biased.
        clientHangSimulator =
            () -> {
              if (ThreadLocalRandom.current().nextInt(1001) % 1000 == 0) {
                try {
                  Thread.sleep(500L);
                } catch (InterruptedException e) {
                  Thread.currentThread().interrupt();
                }
              }
            };
      }
      executorService.execute(new DataGeneratorTask(clientHangSimulator));
    }

    workerThread.start();

    try {
      barrier.await();
      System.out.println("Fired test");
      Thread.sleep(1000);
      executorService.shutdown();
      // runs actually much faster, may need update if item count per client is drastically
      // increased in app.properties
      executorService.awaitTermination(2 * 60, TimeUnit.SECONDS);
      System.out.println("exe service awaited");
    } catch (InterruptedException | BrokenBarrierException e) {
      e.printStackTrace();
    }

    try {
      workerThread.join(Long.MAX_VALUE);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    Assert.assertEquals(
        "Sum generated does not match sum received",
        sumAppender.getSum(),
        AppContext.getInstance().getTotalGeneratedAmount());
    Assert.assertFalse("Worker didn't exit successfully", workerThread.isAlive());
  }
  /*
      Use this version for fire and forget style messaging.
  */
  public void sendOneWay(Message message, EndPoint to) {
    // do local deliveries
    if (message.getFrom().equals(to)) {
      MessagingService.receive(message);
      return;
    }

    Runnable tcpWriteEvent = new MessageSerializationTask(message, to);
    messageSerializerExecutor_.execute(tcpWriteEvent);
  }
Exemple #26
0
 public static void main(String[] args) {
   Random rand = new Random(47);
   ExecutorService exec = Executors.newCachedThreadPool();
   DelayQueue<DelayedTask> queue = new DelayQueue<DelayedTask>();
   // Fill with tasks that have random delays:
   for (int i = 0; i < 20; i++) queue.put(new DelayedTask(rand.nextInt(5000)));
   // Set the stopping point
   queue.add(new DelayedTask.EndSentinel(5000, exec));
   exec.execute(new DelayedTaskConsumer(queue));
 }
  protected <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
      throws InterruptedException, ExecutionException, TimeoutException {

    FutureTask<T> task = new FutureTask<T>(c);
    try {
      THREAD_POOL.execute(task);
      return task.get(timeout, timeUnit);
    } finally {
      task.cancel(true);
    }
  }
  public void serve() {
    try {
      serverTransport_.listen();
    } catch (TTransportException ttx) {
      LOGGER.error("Error occurred during listening.", ttx);
      return;
    }

    stopped_ = false;
    while (!stopped_) {
      int failureCount = 0;
      try {
        TTransport client = serverTransport_.accept();
        WorkerProcess wp = new WorkerProcess(client);
        try {
          executorService_.execute(wp);
        } catch (RejectedExecutionException ree) {
          ++failureCount;
          LOGGER.warn("Execution rejected.", ree);
          client.close();
        }
      } catch (TTransportException ttx) {
        if (!stopped_) {
          ++failureCount;
          LOGGER.warn("Transport error occurred during acceptance of message.", ttx);
        }
      } catch (Error e) {
        if (!stopped_) {
          ++failureCount;
          LOGGER.warn("Uncaught error.", e);
        }
      }
    }

    executorService_.shutdown();

    // Loop until awaitTermination finally does return without a interrupted
    // exception. If we don't do this, then we'll shut down prematurely. We want
    // to let the executorService clear it's task queue, closing client sockets
    // appropriately.
    long timeoutMS = options_.stopTimeoutUnit.toMillis(options_.stopTimeoutVal);
    long now = System.currentTimeMillis();
    while (timeoutMS >= 0) {
      try {
        executorService_.awaitTermination(timeoutMS, TimeUnit.MILLISECONDS);
        break;
      } catch (InterruptedException ix) {
        long newnow = System.currentTimeMillis();
        timeoutMS -= (newnow - now);
        now = newnow;
      }
    }
  }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   Restaurant restaurant = new Restaurant(exec, 5, 2);
   exec.execute(restaurant);
   if (args.length > 0) // Optional argument
   TimeUnit.SECONDS.sleep(new Integer(args[0]));
   else {
     print("Press ‘Enter’ to quit");
     System.in.read();
   }
   exec.shutdownNow();
 }
 public static void main(String[] args) {
   ExecutorService exec = Executors.newCachedThreadPool();
   AtomicityTest at = new AtomicityTest();
   exec.execute(at);
   while (true) {
     int val = at.getValue();
     if (val % 2 != 0) {
       System.out.println(val);
       System.exit(0);
     }
   }
 }