private BenchmarkTcpClient(final String host, final int port)
     throws IOException, InterruptedException {
   super();
   final Thread eventLoopThread = eventLoop.start();
   eventLoop.connect(new InetSocketAddress(host, port), this);
   eventLoopThread.join();
 }
Ejemplo n.º 2
0
  // Private since we can't add a vtable slot in 4.1.x.
  private void exitNoChecks(int status) {
    if (runShutdownHooks()) exitInternal(status);

    // Someone else already called runShutdownHooks().
    // Make sure we are not/no longer in the shutdownHooks set.
    // And wait till the thread that is calling runShutdownHooks() finishes.
    synchronized (libpath) {
      if (shutdownHooks != null) {
        shutdownHooks.remove(Thread.currentThread());
        // Interrupt the exit sequence thread, in case it was waiting
        // inside a join on our thread.
        exitSequence.interrupt();
        // Shutdown hooks are still running, so we clear status to
        // make sure we don't halt.
        status = 0;
      }
    }

    // If exit() is called again after the shutdown hooks have run, but
    // while finalization for exit is going on and the status is non-zero
    // we halt immediately.
    if (status != 0) exitInternal(status);

    while (true)
      try {
        exitSequence.join();
      } catch (InterruptedException e) {
        // Ignore, we've suspended indefinitely to let all shutdown
        // hooks complete, and to let any non-zero exits through, because
        // this is a duplicate call to exit(0).
      }
  }
Ejemplo n.º 3
0
  public static void main(String[] args) {

    ThreadGroup group = new ThreadGroup("demo");

    for (int i = 0; i < 3; i++) {
      new Thread(
              group,
              new Runnable() {
                public void run() {
                  System.out.print("");
                }
              })
          .start();
    }
    group.list();
    int count = group.activeCount(); // 获得线程组中活动的线程
    System.out.println(count);
    Thread threads[] = new Thread[group.activeCount()];
    group.enumerate(threads); // 将当前线程组中活动的线程复制到一个线程数组中去。

    for (Thread thread : threads) {
      System.out.println(thread.getName());
    }
    ThreadGroup parent = group.getParent();

    parent.list();
    ThreadGroup parent2 = parent.getParent();
    parent2.list();
  }
  public void testListenerDoesntDeadlockOnStopAndWaitFromTerminated() throws Exception {
    final NoOpThreadedService service = new NoOpThreadedService();
    service.addListener(
        new Listener() {
          @Override
          public void starting() {}

          @Override
          public void running() {}

          @Override
          public void stopping(State from) {}

          @Override
          public void terminated(State from) {
            service.stopAndWait();
          }

          @Override
          public void failed(State from, Throwable failure) {}
        },
        MoreExecutors.sameThreadExecutor());
    service.startAndWait();

    Thread thread =
        new Thread() {
          @Override
          public void run() {
            service.stopAndWait();
          }
        };
    thread.start();
    thread.join(100);
    assertFalse(thread + " is deadlocked", thread.isAlive());
  }
  public static void main(String args[]) {
    DatagramSocket skt = null;
    try {
      skt = new DatagramSocket(6789);
      byte[] buffer = new byte[1000];
      while (true) {
        DatagramPacket request = new DatagramPacket(buffer, buffer.length);
        skt.receive(request);
        System.out.println("Data received from client");
        System.out.println(new String(request.getData()));
        Thread.sleep(15000);

        String[] arrayMsg = (new String(request.getData())).split(" ");

        System.out.println(arrayMsg[0] + "server processed");

        byte[] sendMsg = (arrayMsg[0] + "server processed").getBytes();

        DatagramPacket reply =
            new DatagramPacket(sendMsg, sendMsg.length, request.getAddress(), request.getPort());

        System.out.println("sending data from server to client");
        Thread.sleep(15000);
        ;
        skt.send(reply);
      }
    } catch (Exception e) {

    }
  }
  public static void main(String[] args) throws InterruptedException, IOException {
    System.setProperty("java.net.preferIPv4Stack", "true");
    TransactionProcessor transProcessor = new TransactionProcessor();
    transProcessor.getId();
    System.out.println(
        "Transaction Processor id " + transProcessor.id + " waiting to be activated");
    new Thread() {
      public void run() {
        for (int i = 0; i < 4; i++) {
          transProcessor.updatePeers(transProcessor.id, 0);
          try {
            sleep(peersUpdateInterval);
          } catch (InterruptedException ex) {
            Logger.getLogger(TransactionProcessor.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
      }
    }.start();

    transProcessor.listenMulticast();

    Thread t = new Thread(transProcessor);
    t.setUncaughtExceptionHandler(transProcessor.h);
    t.start();
    while (true) {
      transProcessor.sendAliveSignal();
      Thread.sleep(transProcessor.sendingInverval);
    }
  }
Ejemplo n.º 7
0
 public synchronized void start() {
   if (thread != null) {
     throw new IllegalStateException("already running");
   }
   thread = new Thread(ThreadGroup.systemThreadGroup, this, getClass().getSimpleName());
   thread.setDaemon(true);
   thread.start();
 }
Ejemplo n.º 8
0
 /**
  * As the result of Updater output depends on the thread's completion, it is necessary to wait for
  * the thread to finish before alloowing anyone to check the result.
  */
 public void waitForThread() {
   if (thread.isAlive()) {
     try {
       thread.join();
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
 }
 private void invokeOnExecutionThreadForTest(Runnable runnable) {
   executionThread = new Thread(runnable);
   executionThread.setUncaughtExceptionHandler(
       new UncaughtExceptionHandler() {
         @Override
         public void uncaughtException(Thread thread, Throwable e) {
           thrownByExecutionThread = e;
         }
       });
   executionThread.start();
 }
 protected void closeUnusedWebdrivers() {
   for (Thread thread : ALL_WEB_DRIVERS_THREADS) {
     if (!thread.isAlive()) {
       log.info(
           "Thread "
               + thread.getId()
               + " is dead. Let's close webdriver "
               + THREAD_WEB_DRIVER.get(thread.getId()));
       closeWebDriver(thread);
     }
   }
 }
Ejemplo n.º 11
0
  public void test(TestHarness th) {
    try {
      Thread t = new RuntimeExceptionThread();
      t.start();
      t.join();
      result = true;
    } catch (InterruptedException e) {
      th.fail("unexpected InterruptedException");
    }

    th.check(result);
  }
 @Override
 public void run() {
   while (true) {
     closeUnusedWebdrivers();
     try {
       Thread.sleep(100);
     } catch (InterruptedException e) {
       Thread.currentThread().interrupt();
       break;
     }
   }
 }
 @Override
 public void evaluate() throws Throwable {
   Runnable callSystemExit =
       new Runnable() {
         public void run() {
           System.exit(ARBITRARY_EXIT_STATUS);
         }
       };
   Thread thread = new Thread(callSystemExit);
   thread.start();
   sleep(1000); // wait until the thread exits
 }
Ejemplo n.º 14
0
  public static void main(String... args) {
    final PrintManager printManager = new PrintManager();

    final Thread consumer =
        new Thread(
            new Runnable() {

              public void run() {
                int count = 0;
                while (count++ < 25) {
                  try {
                    sleep(nextInt(1000));
                    yield();
                  } catch (InterruptedException e) {
                    e
                        .printStackTrace(); // To change body of catch statement use File | Settings
                                            // | File Templates.
                  }
                  printManager.printMessage();
                }
              }
            },
            "consumerThread");

    Thread producer =
        new Thread(
            new Runnable() {

              public void run() {
                int count = 0;
                while (count < 25) {
                  try {
                    sleep(nextInt(1000));
                    yield();
                  } catch (InterruptedException e) {
                    e
                        .printStackTrace(); // To change body of catch statement use File | Settings
                                            // | File Templates.
                  }
                  printManager.spoolMessage(format("printout%s", ++count));
                }
                //                System.out.println("Printing finished, interrupting
                // consumers...");
                //                consumer.interrupt();

              }
            },
            "producerThread");

    consumer.start();
    producer.start();
  }
Ejemplo n.º 15
0
 @Override
 public void run() {
   int i = 0;
   while (i < 4) {
     try {
       Thread.sleep(500);
       System.out.println("Je suis : " + Thread.currentThread().getName());
     } catch (InterruptedException ie) {
       System.out.println("Nous avons un problème");
     }
     i++;
   }
 }
    @Override
    public void execute() {
      Random rand = new Random();
      rand.setSeed(System.currentTimeMillis());
      Integer divisor = rand.nextInt(100);
      System.out.println("Request Read by Thread id=" + Thread.currentThread().getId());
      try {
        transactionQueue.put(divisor);
        Thread.sleep(100);
      } catch (InterruptedException e) {

      }
    }
Ejemplo n.º 17
0
 static ClassLoader setThreadContextClassLoader(Class cl) {
   if (getSecurityManager() == null) {
     final Thread thread = currentThread();
     try {
       return thread.getContextClassLoader();
     } finally {
       thread.setContextClassLoader(cl.getClassLoader());
     }
   } else {
     return doPrivileged(
         new SetContextClassLoaderAction(doPrivileged(new GetClassLoaderAction(cl))));
   }
 }
Ejemplo n.º 18
0
  /** Creates a new instance of Remindable */
  public Remindable(java.sql.Connection connDB) {

    java.lang.Thread reminderThread = new java.lang.Thread(this, "Remindables.Thread");

    connectDB = connDB;

    reminderContainer = new biz.systempartners.reminders.ReminderContainer();

    defaultTip = this.getTipsArray(getListofReminders("SELECT * FROM xray"));

    reminderThread.start();

    reminderContainer.showTipOfday();
  }
Ejemplo n.º 19
0
  @Override
  public void actionPerformed(ActionEvent e) {
    // 对用户不同的选择做出不同的处理
    if (e.getActionCommand().equals("new game")) {
      // 创建游戏界面面板
      mp = new MyPanel("newGame");
      // 启动MyPanel线程
      Thread t = new Thread(mp);
      t.start();
      // 先删除旧Panel
      this.remove(msp);
      this.add(mp);
      // 注册监听
      this.addKeyListener(mp);
      // 显示(刷新JFrame)
      this.setVisible(true);

    } else if (e.getActionCommand().equals("exit")) {
      // 用户点击了退出系统菜单
      // 保存击毁敌人数量.
      Recorder.SaveRecord();

      System.exit(0);
    } // 对存盘退出做处理
    else if (e.getActionCommand().equals("saveExit")) {
      Recorder rd = new Recorder();
      rd.setEts(mp.enemyTanks);
      // 保存击毁敌人的数量和敌人的坐标
      rd.SaveRecAndEnemy();

      // 退出(0代表正常退出,1代表异常退出)
      System.exit(0);
    } else if (e.getActionCommand().equals("continue")) {
      //
      // 创建游戏界面面板
      mp = new MyPanel("con");
      //            mp.flag="con";

      // 启动MyPanel线程
      Thread t = new Thread(mp);
      t.start();
      // 先删除旧Panel
      this.remove(msp);
      this.add(mp);
      // 注册监听
      this.addKeyListener(mp);
      // 显示(刷新JFrame)
      this.setVisible(true);
    }
  }
Ejemplo n.º 20
0
  public static void audioStartThread() {
    mAudioThread =
        new Thread(
            new Runnable() {
              public void run() {
                mAudioTrack.play();
                nativeRunAudioThread();
              }
            });

    // I'd take REALTIME if I could get it!
    mAudioThread.setPriority(Thread.MAX_PRIORITY);
    mAudioThread.start();
  }
Ejemplo n.º 21
0
  public static void ReportDistributiveSort(int n) {
    if (sortingThread != null && sortingThread.isAlive()) return;
    int bas = 10;
    if (n != 3 && !(n >= 5))
      if (n != 4)
        try {
          bas = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Base for Sort"));
        } catch (Exception e) {
        }
      else
        try {
          bas = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter Size of Partitions"));
        } catch (Exception e) {
        }

    final int base = Math.max(bas, 2);
    final int num = n;
    SetSound(true);
    sortingThread =
        new Thread() {
          @Override
          public void run() {
            try {
              refresharray();
              heading = DistributiveSorts[num] + " Sort";
              switch (num) {
                case 0:
                  radixLSDsort(base);
                  break;
                case 1:
                  radixMSDSort(base);
                  break;
                case 2:
                  RadixLSDInPlace.inPlaceRadixLSDSort(base);
                  break;
                case 3:
                  gravitySort();
                  break;
                case 4:
                  shatterSort(base);
                  break;
              }
            } catch (Exception e) {
            }
            SetSound(false);
          }
        };
    sortingThread.start();
  }
Ejemplo n.º 22
0
  public static void ReportComparativeSort(int n) {
    if (sortingThread != null && sortingThread.isAlive()) return;

    final int num = n;
    SetSound(true);
    sortingThread =
        new Thread() {
          @Override
          public void run() {
            try {

              refresharray();
              heading = ComparativeSorts[num] + " Sort";
              switch (num) {
                case 0:
                  selectionSort();
                  break;
                case 1:
                  bubbleSort();
                  break;
                case 2:
                  insertionSort();
                  break;
                case 3:
                  doubleSelectionSort(array);
                  break;
                case 4:
                  cocktailShakerSort();
                  break;
                case 5:
                  quickSort(array, 0, array.length - 1);
                  break;
                case 6:
                  mergeSort(0, array.length - 1);
                  break;
                case 7:
                  mergeSortOP();
                  break;
                case 8:
                  weaveMergeSort(0, array.length - 1);
                  break;
              }
            } catch (Exception e) {
            }
            SetSound(false);
          }
        };
    sortingThread.start();
  }
Ejemplo n.º 23
0
  public static void main(String[] args) throws InterruptedException {

    Thread t[] = new Thread[6]; // 6 Threads are tested

    System.out.println("*** Bank Account Test***");
    System.out.println("");
    System.out.println("Creation of the Gianluca Carroccia's account");
    System.out.println("");

    BankAccount accounts[] = new BankAccount[1]; // accounts' array
    accounts[0] = new BankAccount(1, "pwd", 1000, "Gianluca", "Carroccia"); // my account

    System.out.println("Thread 1: deposit £10, 100 times with the right password");
    t[0] =
        new Thread(
            new Transaction(accounts[0], "pwd", "deposit", 10, 100)); // creation of a new Thread
    // performing a specific transaction

    System.out.println("Thread 2: withdrow £15, 100 times with the right password");
    t[1] = new Thread(new Transaction(accounts[0], "pwd", "withdraw", 15, 100));

    System.out.println("Thread 3: show the balance, 100 times with the right password");
    t[2] = new Thread(new Transaction(accounts[0], "pwd", "balance", 100));

    System.out.println("Thread 4: deposit £10, 50 times with the wrong password");
    t[3] = new Thread(new Transaction(accounts[0], "wrong pwd", "deposit", 10, 50));

    System.out.println("Thread 5: deposit £10, 50 times with the wrong password");
    t[4] = new Thread(new Transaction(accounts[0], "wrong pwd", "withdraw", 10, 50));

    System.out.println("Thread 6: show the balance, 50 times with the wrong password");
    t[5] = new Thread(new Transaction(accounts[0], "wrong pwd", "balance", 50));

    System.out.println("");

    for (int i = 0; i < 6; i++) { // starts the Threads
      t[i].start();
    }

    for (int i = 0; i < 6; i++) { // wait for the Threads end
      t[i].join();
    }

    System.out.println("");
    System.out.println("");
    Thread tBalance =
        new Thread(new Transaction(accounts[0], "pwd", "balance", 1)); // show the final balance
    tBalance.start();
  }
Ejemplo n.º 24
0
 /**
  * Register a new shutdown hook. This is invoked when the program exits normally (because all
  * non-daemon threads ended, or because <code>System.exit</code> was invoked), or when the user
  * terminates the virtual machine (such as by typing ^C, or logging off). There is a security
  * check to add hooks, <code>RuntimePermission("shutdownHooks")</code>.
  *
  * <p>The hook must be an initialized, but unstarted Thread. The threads are run concurrently, and
  * started in an arbitrary order; and user threads or daemons may still be running. Once shutdown
  * hooks have started, they must all complete, or else you must use <code>halt</code>, to actually
  * finish the shutdown sequence. Attempts to modify hooks after shutdown has started result in
  * IllegalStateExceptions.
  *
  * <p>It is imperative that you code shutdown hooks defensively, as you do not want to deadlock,
  * and have no idea what other hooks will be running concurrently. It is also a good idea to
  * finish quickly, as the virtual machine really wants to shut down!
  *
  * <p>There are no guarantees that such hooks will run, as there are ways to forcibly kill a
  * process. But in such a drastic case, shutdown hooks would do little for you in the first place.
  *
  * @param hook an initialized, unstarted Thread
  * @throws IllegalArgumentException if the hook is already registered or run
  * @throws IllegalStateException if the virtual machine is already in the shutdown sequence
  * @throws SecurityException if permission is denied
  * @since 1.3
  * @see #removeShutdownHook(Thread)
  * @see #exit(int)
  * @see #halt(int)
  */
 public void addShutdownHook(Thread hook) {
   SecurityManager sm = SecurityManager.current; // Be thread-safe!
   if (sm != null) sm.checkPermission(new RuntimePermission("shutdownHooks"));
   if (hook.isAlive() || hook.getThreadGroup() == null)
     throw new IllegalArgumentException(
         "The hook thread " + hook + " must not have been already run or started");
   synchronized (libpath) {
     if (exitSequence != null)
       throw new IllegalStateException(
           "The Virtual Machine is exiting. It is not possible anymore to add any hooks");
     if (shutdownHooks == null) shutdownHooks = new HashSet(); // Lazy initialization.
     if (!shutdownHooks.add(hook))
       throw new IllegalArgumentException(hook.toString() + " had already been inserted");
   }
 }
Ejemplo n.º 25
0
  public static void main(String[] args) throws LBMException {
    LBMContext ctx = null; /* Context object: container for UM "instance". */
    LBMSource src = null; /* Source object: for sending messages. */

    SrcCB srccb = new SrcCB();

    /** * Initialization: create necessary UM objects. ** */
    try {
      LBMTopic topic = null;
      LBMSourceAttributes srcAttr = null;

      ctx = new LBMContext();
      srcAttr = new LBMSourceAttributes();
      srcAttr.setValue("ume_store", "127.0.0.1:29999");
      srcAttr.setValue("ume_store_behavior", "qc");
      topic = ctx.allocTopic("test.topic", srcAttr);
      src = ctx.createSource(topic, srccb, null, null);
    } catch (LBMException ex) {
      System.err.println("Error initializing LBM objects: " + ex.toString());
      System.exit(1);
    }

    while (true) {
      if (srcReady == 1) {
        /** * Send a message. ** */
        try {
          src.send("test".getBytes(), "test".getBytes().length, LBM.MSG_FLUSH | LBM.SRC_NONBLOCK);
        } catch (LBMException ex) {
          /* Error trying to send, wait 1 second and try again */
          try {
            Thread.sleep(1000);
          } catch (InterruptedException tex) {
            System.err.println("Error Thread.sleep interrupted: " + tex.toString());
            System.exit(1);
          }
        }
      } else {
        /* No quorum, wait 1 second and check again */
        System.out.println("Source is not ready to send (no quorum)");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException tex) {
          System.err.println("Error Thread.sleep interrupted: " + tex.toString());
          System.exit(1);
        }
      }
    }
  } /* main */
Ejemplo n.º 26
0
  /**
   * sleep some
   *
   * @param time
   */
  public void sleep(int time) {
    try {
      java.lang.Thread.sleep(time);
    } catch (InterruptedException e) {

    }
  }
Ejemplo n.º 27
0
  public void run() {

    System.out.println("System has entered running mode");

    while (threadCheck) {

      System.out.println("O.K. see how we execute target program");

      this.generatePdf();

      try {

        System.out.println("Right, let's wait for task to complete of fail");

        java.lang.Thread.currentThread().sleep(200);

        System.out.println("It's time for us threads to get back to work after the nap");

      } catch (java.lang.InterruptedException IntExec) {

        System.out.println(IntExec.getMessage());
      }

      threadCheck = false;

      System.out.println("We shall be lucky to get back to start in one piece");
    }

    if (!threadCheck) {

      Thread.currentThread().stop();
    }
  }
Ejemplo n.º 28
0
  public void RevenuePriceListPdf(
      java.sql.Connection connDb,
      java.util.Date begindate,
      java.util.Date endate,
      java.lang.String combox) {
    // public void StoresBalPdf(java.sql.Connection connDb) {

    dbObject = new com.afrisoftech.lib.DBObject();

    bank = combox;

    connectDB = connDb;

    // beginDate = begindate;

    // endDate = endate;

    threadSample = new java.lang.Thread(this, "SampleThread");

    System.out.println("threadSample created");

    threadSample.start();

    System.out.println("threadSample fired");
  }
Ejemplo n.º 29
0
  private boolean connectSPPMon() {
    if (state == ConnectionEvent.CONNECTION_PENDING) {
      ExpCoordinator.print(
          new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0);
      while (state == ConnectionEvent.CONNECTION_PENDING) {
        try {
          Thread.sleep(500);
        } catch (java.lang.InterruptedException e) {
        }
      }
      return (isConnected());
    }

    state = ConnectionEvent.CONNECTION_PENDING;
    if (nonProxy != null) {
      try {
        nonProxy.connect();
      } catch (UnknownHostException e) {
        boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage());
        return rtn;
      } catch (SocketTimeoutException e) {
        boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage());
        return rtn;
      } catch (IOException e) {
        boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage());
        return rtn;
      }
    }
    return (isConnected());
  }
  public SurefireProvider createProvider(boolean isInsideFork) {
    ClassLoader systemClassLoader = java.lang.Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(classLoader);

    StartupConfiguration starterConfiguration = startupConfiguration;

    // Note: Duplicated in ForkedBooter#createProviderInCurrentClassloader
    final Object o =
        surefireReflector.createBooterConfiguration(
            classLoader, reporterManagerFactory, isInsideFork);
    surefireReflector.setTestSuiteDefinitionAware(
        o, providerConfiguration.getTestSuiteDefinition());
    surefireReflector.setProviderPropertiesAware(o, providerConfiguration.getProviderProperties());
    surefireReflector.setReporterConfigurationAware(
        o, providerConfiguration.getReporterConfiguration());
    surefireReflector.setTestClassLoaderAware(o, classLoader);
    surefireReflector.setTestArtifactInfoAware(o, providerConfiguration.getTestArtifact());
    surefireReflector.setRunOrderParameters(o, providerConfiguration.getRunOrderParameters());
    surefireReflector.setIfDirScannerAware(o, providerConfiguration.getDirScannerParams());

    Object provider =
        surefireReflector.instantiateProvider(starterConfiguration.getActualClassName(), o);
    Thread.currentThread().setContextClassLoader(systemClassLoader);

    return new ProviderProxy(provider, classLoader);
  }