コード例 #1
1
 /** Implementation of Runnable interface. DO NOT access this method directly. */
 public void run() {
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       true); // animated frames are updated by this thread so no need to repaint
   long sleepTime = delayTime;
   while (animationThread == Thread.currentThread()) {
     long currentTime = System.currentTimeMillis();
     for (int i = 0; i < stepsPerDisplay; i++) {
       doStep();
       stepCounter++;
       if (animationThread != Thread.currentThread()) {
         break; // check for stop condition
       } else {
         Thread.yield(); // give other threads a chance to run if needed
       }
     }
     org.opensourcephysics.display.GUIUtils.renderAnimatedFrames();
     // adjust the sleep time to try and achieve a constant animation rate
     // some VMs will hang if sleep time is less than 10
     sleepTime = Math.max(10, delayTime - (System.currentTimeMillis() - currentTime));
     try {
       Thread.sleep(sleepTime);
     } catch (InterruptedException ie) {
     }
   }
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       false); // animated frames are updated by this thread so no need to repaint
 }
コード例 #2
0
ファイル: MsnTreeTest.java プロジェクト: hbt/jmsnmessenger
  public static void main(String[] args) {
    //        BuddyTree buddy;
    Properties prop;
    msn = new MSNMessenger("*****@*****.**", "marinescommand");

    msn.setInitialStatus(UserStatus.ONLINE);
    msn.addMsnListener(new MSNAdapter(msn));
    msn.login();

    System.out.println("Waiting for the response....");

    MsnTreeTest test = new MsnTreeTest();
    try {
      Thread.currentThread().sleep(6000);
    } catch (InterruptedException ex) {
    }
    if (msn.isLoggedIn()) {
      BuddyList bl = msn.getBuddyGroup().getForwardList();
      for (int i = 0; i < bl.size(); i++) {
        if (!bl.get(i).getStatus().equalsIgnoreCase(UserStatus.OFFLINE)) {
          System.out.println(bl.get(i).getLoginName());
        } else {
          System.out.println("User offline: " + bl.get(i).getLoginName());
        }
      }
    } else {
      System.out.println("terminator");
    }
  }
コード例 #3
0
    /**
     * @return String from the page
     * @throws Exception
     */
    private static String GetPHRAZE() throws Exception {
      String PHRAZE = "";
      try {
        URLConnection connection =
            new java.net.URL(Settings.GET_PANEL_URL() + "?key=" + Settings.GET_PANEL_KEYPHRAZE())
                .openConnection();
        InputStream ist = connection.getInputStream();
        InputStreamReader reader = new InputStreamReader(ist);
        char[] buffer = new char[256];
        int rc;
        StringBuilder sb = new StringBuilder();
        while ((rc = reader.read(buffer)) != -1) sb.append(buffer, 0, rc);
        reader.close();
        PHRAZE = String.valueOf(sb);
      } catch (Exception e) {

        PRINT("ERROR: " + e.toString() + " [Methods::OpenURL]", 1);
        // Thread.currentThread().stop();
        Thread.currentThread().interrupt();
        return "";
      }

      if (Settings.GET_DO_ONLY_ONCE()) {
        if (Objects.equals(PHRAZE, PREVIOUS_PHRAZE)) {
          Thread.currentThread().interrupt();
          return "";
        } else {
          PREVIOUS_PHRAZE = PHRAZE;
        }
      }
      return PHRAZE;
    }
コード例 #4
0
 public void dispose() {
   LOG.assertTrue(EventQueue.isDispatchThread(), Thread.currentThread().getName());
   myAbstractTreeBuilder = null;
   // this will also dispose wrapped TreeModel
   myTreeModelWrapper.dispose();
   myFileEditor = null;
 }
コード例 #5
0
 public void run() {
   try {
     thread.sleep(1111);
   } catch (Exception e) {
     return;
   }
   Thread me = Thread.currentThread();
   while (thread == me) {
     for (int i = 0; i < ImageOps.imgName.length; i++) {
       imgCombo.setSelectedIndex(i);
       for (int j = 0; j < ImageOps.opsName.length; j++) {
         opsCombo.setSelectedIndex(j);
         if (j <= 1) {
           for (int k = 50; k <= 200; k += 10) {
             demo.slider1.setValue(k);
             try {
               thread.sleep(200);
             } catch (InterruptedException e) {
               return;
             }
           }
         }
         try {
           thread.sleep(4444);
         } catch (InterruptedException e) {
           return;
         }
       }
     }
   }
   thread = null;
 }
コード例 #6
0
  /**
   * Tests out the panel from the command line.
   *
   * @param args ignored.
   */
  public static void main(String[] args) {

    try {
      final JFrame jf = new JFrame("Generator Property Iterator");
      jf.getContentPane().setLayout(new BorderLayout());
      GeneratorPropertyIteratorPanel gp = new GeneratorPropertyIteratorPanel();
      jf.getContentPane().add(gp, BorderLayout.CENTER);
      jf.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              jf.dispose();
              System.exit(0);
            }
          });
      jf.pack();
      jf.setVisible(true);
      System.err.println("Short nap");
      Thread.currentThread().sleep(3000);
      System.err.println("Done");
      gp.setExperiment(new Experiment());
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(ex.getMessage());
    }
  }
コード例 #7
0
  public static void main(String[] args) {
    JFrame frame = new JFrame("options");

    frame.setSize(new Dimension(500, 300));
    frame.getContentPane().add(new PackagerOptionsPanel(null));

    frame.addWindowListener(
        new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
            e.getWindow().dispose();
          }

          @Override
          public void windowClosed(WindowEvent e) {
            System.exit(0);
          }
        });

    try {
      SwingUtilities.invokeAndWait(new PackAndShowFrameWorker(frame));
    } catch (InterruptedException e) {
      // Immediately reasserts the exception by interrupting the caller thread itself
      Thread.currentThread().interrupt();

      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
コード例 #8
0
  @Override
  public synchronized void run() {
    try {
      for (int i = 0; i < NUM_PIPES; i++) {
        while (Thread.currentThread() == reader[i]) {
          try {
            this.wait(100);
          } catch (InterruptedException ie) {
          }
          if (pin[i].available() != 0) {
            String input = this.readLine(pin[i]);
            appendMsg(htmlize(input));
            if (textArea.getDocument().getLength() > 0) {
              textArea.setCaretPosition(textArea.getDocument().getLength() - 1);
            }
          }
          if (quit) {
            return;
          }
        }
      }

    } catch (Exception e) {
      Debug.error(me + "Console reports an internal error:\n%s", e.getMessage());
    }
  }
コード例 #9
0
 public void run() {
   int tmprCount = 0;
   boolean running = true;
   for (runCount = 0; runCount < maxRun; runCount++) {
     running = (runner == Thread.currentThread());
     if (running) {
       initialise();
       saveCA();
       iterations++;
       while ((iterations < maxit)) {
         experiment.iterate();
         saveCA();
         drawCA();
         // if ((runCount%10) == 0)
         // drawLines();
         iterations++;
         // newframe = 0;
         // while(newframe<500000) newframe++;
         // if((iterations%5)==0)postscriptPrint("CA"+iterations+".eps");
         // This will produce a postscript output of the tissue
       }
       tmprCount = runCount;
       saveStats();
       // if ((runCount%25) == 0) drawLines(maxit,runCount);
     }
   }
   // this will print out aborted results
   // to stop that check if maxit was achieved
   if (!started) runCount = tmprCount + 1; // just in case stop was pressed
   // iterations should anyway be equal to maxit
   showStats();
   stop();
 }
コード例 #10
0
  @Override
  public boolean isSoftWrappingEnabled() {
    if (!myUseSoftWraps
        || (!myEditor.myUseNewRendering && myEditor.isOneLineMode())
        || myEditor.isPurePaintingMode()) {
      return false;
    }

    // We check that current thread is EDT because attempt to retrieve information about visible
    // area width may fail otherwise
    Application application = ApplicationManager.getApplication();
    Thread lastEdt = myLastEdt.get();
    Thread currentThread = Thread.currentThread();
    if (lastEdt != currentThread) {
      if (application.isDispatchThread()) {
        myLastEdt = new SoftReference<Thread>(currentThread);
      } else {
        myLastEdt = new SoftReference<Thread>(null);
        return false;
      }
    }

    Rectangle visibleArea = myEditor.getScrollingModel().getVisibleArea();
    return visibleArea.width > 0 && visibleArea.height > 0;
  }
コード例 #11
0
  private void initUI() {

    JPanel infoPanel = new JPanel();
    infoPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    infoPanel.setBackground(Color.WHITE);
    infoPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

    infoPanel.add(
        new JLabel(
            new ImageIcon(
                Thread.currentThread().getContextClassLoader().getResource("siw-logo3_2.gif"))));

    JLabel textLabel = new JLabel("<html>Confirmation</html>");

    infoPanel.add(textLabel);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(0, 1));

    buttonPanel.add(reportLabel);

    this.setLayout(new BorderLayout());
    this.add(infoPanel, BorderLayout.NORTH);
    this.add(buttonPanel, BorderLayout.CENTER);
  }
コード例 #12
0
  private boolean loadWebPage(final JWebBrowser webBrowser) {
    try {
      final String language = Locale.getDefault().getLanguage();
      File html =
          Externalization.extractFile(
              "slash/navigation/converter/gui/mapview/routeconverter.html",
              language,
              new TokenResolver() {
                public String resolveToken(String tokenName) {
                  if (tokenName.equals("locale")) return language;
                  if (tokenName.equals("percent")) return Platform.isWindows() ? "99" : "100";
                  if (tokenName.equals("mapserver"))
                    return preferences.get(MAP_SERVER_PREFERENCE, "maps.google.com");
                  return tokenName;
                }
              });
      if (html == null) throw new IllegalArgumentException("Cannot extract routeconverter.html");
      Externalization.extractFile("slash/navigation/converter/gui/mapview/contextmenucontrol.js");

      final String url = html.toURI().toURL().toExternalForm();
      webBrowser.runInSequence(
          new Runnable() {
            public void run() {
              webBrowser.navigate(url);
            }
          });
      log.fine(System.currentTimeMillis() + " loadWebPage thread " + Thread.currentThread());
    } catch (Throwable t) {
      log.severe("Cannot create WebBrowser: " + t.getMessage());
      setInitializationCause(t);
      return false;
    }
    return true;
  }
コード例 #13
0
  @Override
  public void run() {

    for (int i = 0; i < 4; i++) {
      URL url = getClass().getResource("/images/propeller" + i + ".jpg");
      try {
        images[i] = ImageIO.read(url);
      } catch (IOException ex) {
        ex.printStackTrace();
      }
      // System.out.println("url: " + url.toString());
    }

    // Animation beginnen
    Thread me = Thread.currentThread();
    while (animation == me) {
      try {
        Thread.sleep(50);
      } catch (InterruptedException ex) {
        break;
      }
      synchronized (this) {
        index++;
        // System.out.println("index: " + index);
        if (index >= images.length) index = 0;
      }
      repaint();
    }
  }
コード例 #14
0
ファイル: MainFrame.java プロジェクト: XaoZloHnH/hafen-client
 public void run() {
   if (Thread.currentThread() != this.mt)
     throw (new RuntimeException("MainFrame is being run from an invalid context"));
   Thread ui = new HackThread(p, "Haven UI thread");
   ui.start();
   try {
     try {
       Session sess = null;
       while (true) {
         UI.Runner fun;
         if (sess == null) {
           Bootstrap bill = new Bootstrap(Config.defserv, Config.mainport);
           if ((Config.authuser != null) && (Config.authck != null)) {
             bill.setinitcookie(Config.authuser, Config.authck);
             Config.authck = null;
           }
           fun = bill;
           setTitle(String.format("Amish Paradise %s", version));
         } else {
           fun = new RemoteUI(sess);
           setTitle(String.format("Amish Paradise %s \u2013 %s", version, sess.username));
         }
         sess = fun.run(p.newui(sess));
       }
     } catch (InterruptedException e) {
     }
     savewndstate();
   } finally {
     ui.interrupt();
     dispose();
   }
 }
コード例 #15
0
ファイル: Connection.java プロジェクト: egphilippov/openwood
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
コード例 #16
0
  // Not sure about what happens if multiple of this test are
  //  instantiated in the same VM.  Being static (and using
  //  static vars), it aint gonna work.  Not worrying about
  //  it for now.
  public static void main(String args[]) throws InterruptedException {
    mainThread = Thread.currentThread();
    try {
      init();
    } catch (TestPassedException e) {
      // The test passed, so just return from main and harness will
      // interepret this return as a pass
      return;
    }
    // At this point, neither test pass nor test fail has been
    // called -- either would have thrown an exception and ended the
    // test, so we know we have multiple threads.

    // Test involves other threads, so sleep and wait for them to
    // called pass() or fail()
    try {
      Thread.sleep(sleepTime);
      // Timed out, so fail the test
      throw new RuntimeException("Timed out after " + sleepTime / 1000 + " seconds");
    } catch (InterruptedException e) {
      // The test harness may have interrupted the test.  If so, rethrow the exception
      // so that the harness gets it and deals with it.
      if (!testGeneratedInterrupt) throw e;

      // reset flag in case hit this code more than once for some reason (just safety)
      testGeneratedInterrupt = false;

      if (theTestPassed == false) {
        throw new RuntimeException(failureMessage);
      }
    }
  } // main
コード例 #17
0
ファイル: Check.java プロジェクト: charlesa101/insubstantial
 public static Icon getIcon(String iconName) {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   URL url = cl.getResource("test/check/icons/" + iconName + ".gif");
   if (url != null) return new ImageIcon(url);
   url = cl.getResource("test/check/icons/" + iconName + ".png");
   if (url != null) return new ImageIcon(url);
   return null;
 }
コード例 #18
0
 public boolean isReadAccessAllowed() {
   Thread currentThread = Thread.currentThread();
   return ourDispatchThread == currentThread
       || isExceptionalThreadWithReadAccess()
       || myActionsLock.isReadLockAcquired()
       || myActionsLock.isWriteLockAcquired()
       || isDispatchThread();
 }
コード例 #19
0
 private ArrayList<Shape> getSelectedTextBounds() {
   Page currentPage = pageViewComponent.getPage();
   ArrayList<Shape> highlightBounds = null;
   if (currentPage != null && currentPage.isInitiated()) {
     try {
       PageText pageText = currentPage.getViewText();
       if (pageText != null) {
         // get page transformation
         AffineTransform pageTransform =
             currentPage.getPageTransform(
                 documentViewModel.getPageBoundary(),
                 documentViewModel.getViewRotation(),
                 documentViewModel.getViewZoom());
         // paint the sprites
         GeneralPath textPath;
         ArrayList<LineText> pageLines = pageText.getPageLines();
         if (pageLines != null) {
           for (LineText lineText : pageLines) {
             java.util.List<WordText> words = lineText.getWords();
             if (words != null) {
               for (WordText wordText : words) {
                 // paint whole word
                 if (wordText.isSelected() || wordText.isHighlighted()) {
                   textPath = new GeneralPath(wordText.getBounds());
                   textPath.transform(pageTransform);
                   // paint highlight over any selected
                   if (wordText.isSelected()) {
                     if (highlightBounds == null) {
                       highlightBounds = new ArrayList<Shape>();
                     }
                     highlightBounds.add(textPath.getBounds2D());
                   }
                 }
                 // check children
                 else {
                   for (GlyphText glyph : wordText.getGlyphs()) {
                     if (glyph.isSelected()) {
                       textPath = new GeneralPath(glyph.getBounds());
                       textPath.transform(pageTransform);
                       if (highlightBounds == null) {
                         highlightBounds = new ArrayList<Shape>();
                       }
                       highlightBounds.add(textPath.getBounds2D());
                     }
                   }
                 }
               }
             }
           }
         }
       }
     } catch (InterruptedException e) {
       Thread.currentThread().interrupt();
       logger.fine("HighLightAnnotation selected text bounds calculation interrupted.");
     }
   }
   return highlightBounds;
 }
コード例 #20
0
 public void drainQueuedUsageNodes() {
   assert !ApplicationManager.getApplication().isDispatchThread() : Thread.currentThread();
   UIUtil.invokeAndWaitIfNeeded(
       new Runnable() {
         @Override
         public void run() {
           myTransferToEDTQueue.drain();
         }
       });
 }
コード例 #21
0
  @Override
  public String getThreadId() {
    String threadId = "[" + Thread.currentThread().getId() + "]: ";

    if (null != this.mapSource && null != this.mapSource.getName()) {
      return this.mapSource.getName() + " " + threadId;
    }

    return threadId;
  }
コード例 #22
0
ファイル: StdDraw.java プロジェクト: ihordey/algorithms-4th
 /**
  * Display on screen, pause for t milliseconds, and turn on <em>animation mode</em>: subsequent
  * calls to drawing methods such as <tt>line()</tt>, <tt>circle()</tt>, and <tt>square()</tt> will
  * not be displayed on screen until the next call to <tt>show()</tt>. This is useful for producing
  * animations (clear the screen, draw a bunch of shapes, display on screen for a fixed amount of
  * time, and repeat). It also speeds up drawing a huge number of shapes (call <tt>show(0)</tt> to
  * defer drawing on screen, draw the shapes, and call <tt>show(0)</tt> to display them all on
  * screen at once).
  *
  * @param t number of milliseconds
  */
 public static void show(int t) {
   defer = false;
   draw();
   try {
     Thread.currentThread().sleep(t);
   } catch (InterruptedException e) {
     System.out.println("Error sleeping");
   }
   defer = true;
 }
コード例 #23
0
ファイル: Counterl.java プロジェクト: hulibal/JavaLearning
 public void go() {
   while (true) {
     try {
       Thread.currentThread();
       Thread.sleep(100);
     } catch (InterruptedException e) {
     }
     if (runFlag) t.setText(Integer.toString(count++));
   }
 }
コード例 #24
0
  private static void assertIsDispatchThread(String message) {
    if (ShutDownTracker.isShutdownHookRunning()) return;
    final Thread currentThread = Thread.currentThread();
    if (ourDispatchThread == currentThread) return;

    if (EventQueue.isDispatchThread()) {
      ourDispatchThread = currentThread;
    }
    if (ourDispatchThread == currentThread) return;

    Integer safeCounter = ourEdtSafe.get();
    if (safeCounter != null && safeCounter > 0) return;

    LOG.error(
        message,
        "Current thread: " + describe(Thread.currentThread()),
        "Our dispatch thread:" + describe(ourDispatchThread),
        "SystemEventQueueThread: " + describe(getEventQueueThread()));
  }
コード例 #25
0
 public void assertReadAccessAllowed() {
   if (myHeadlessMode) return;
   if (!isReadAccessAllowed()) {
     LOG.error(
         "Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())",
         "Current thread: " + describe(Thread.currentThread()),
         "Our dispatch thread:" + describe(ourDispatchThread),
         "SystemEventQueueThread: " + describe(getEventQueueThread()));
   }
 }
コード例 #26
0
 private static void waitUntilConnect(@NotNull AndroidDebugBridge bridge) {
   while (!bridge.isConnected() && !Thread.currentThread().isInterrupted()) {
     try {
       //noinspection BusyWait
       Thread.sleep(1000);
     } catch (InterruptedException e) {
       LOG.debug(e);
       return;
     }
   }
 }
コード例 #27
0
 private String getSelectedText() {
   Page currentPage = pageViewComponent.getPage();
   String selectedText = null;
   try {
     selectedText = currentPage.getViewText().getSelected().toString();
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
     logger.fine("HighLightAnnotation initialization interrupted.");
   }
   return selectedText;
 }
コード例 #28
0
ファイル: Connection.java プロジェクト: egphilippov/openwood
  public final String readCommand(byte[] b)
      throws IOException, InterruptedException, MessagingNetworkException {
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;
      boolean d = false;
      for (; ; ) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int by = is.read();
        if (by == -1) throw new IOException("unexpected EOF");
        if (by == 10 && d) break;
        d = (by == 13);
        if (ofs < b.length) {
          b[ofs++] = (byte) by;
        }
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }
      if (b[ofs - 1] == 13) --ofs;

      String line = new String(b, 0, ofs, "ASCII");

      if (StringUtil.startsWith(line, "MSG")) {
        StringTokenizer st = new StringTokenizer(line);
        String len_s = null;
        while (st.hasMoreTokens()) {
          len_s = st.nextToken();
        }
        if (len_s == null) throw new AssertException("len_s is null");
        int len;
        try {
          len = Integer.parseInt(len_s);
        } catch (NumberFormatException ex) {
          ServerConnection.throwProtocolViolated("MSG length must be int");
          len = 0;
        }
        String msg = readMSG(len);
        line = line + "\r\n" + msg;
      }
      if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("S: " + line);
      return line;
    }
  }
コード例 #29
0
ファイル: Sayac.java プロジェクト: maeyler/PlainJava
 public void run() {
   System.out.println("start");
   while (Thread.currentThread() == thd) {
     try {
       setDate();
       Thread.sleep(10 * 1000);
     } catch (InterruptedException e) {
     }
   }
   System.out.println("Stop");
 }
コード例 #30
0
ファイル: Connection.java プロジェクト: egphilippov/openwood
 public final void writeASCII(String s) throws IOException {
   if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
   OutputStream os = getOutputStream();
   synchronized (os) {
     if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("C: " + s);
     os.write(s.getBytes("ASCII"));
     os.write((byte) 13);
     os.write((byte) 10);
     os.flush();
   }
 }