/** * Disconnect a mavlink connection. If the operation is successful, it will be reported through * the MavLinkConnectionListener interface. */ public void disconnect() { if (mConnectionStatus.get() == MAVLINK_DISCONNECTED || (mConnectThread == null && mTaskThread == null)) { return; } try { final long disconnectTime = System.currentTimeMillis(); mConnectionStatus.set(MAVLINK_DISCONNECTED); mConnectionTime.set(-1); if (mConnectThread != null && mConnectThread.isAlive() && !mConnectThread.isInterrupted()) { mConnectThread.interrupt(); } if (mTaskThread != null && mTaskThread.isAlive() && !mTaskThread.isInterrupted()) { mTaskThread.interrupt(); } closeConnection(); reportDisconnect(disconnectTime); } catch (IOException e) { mLogger.logErr(TAG, e); reportComError(e.getMessage()); } }
/** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread() { @Override public void run() { long i = 0l; try { while (this.isInterrupted() == false) { System.out.println(Thread.currentThread().getName() + " sleep 10 "); TimeUnit.SECONDS.sleep(10); } } catch (InterruptedException e) // 会抛出InterruptException因为Sleep会阻塞 { e.printStackTrace(); System.out.println(Thread.currentThread().getName() + ":" + e.getMessage()); } } }; Thread t2 = new Thread() { @Override public void run() { long i = 0l; while (this.isInterrupted() == false) { try { Thread.currentThread().sleep(1); i++; while (true) { i++; } } catch (InterruptedException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }; t1.start(); t2.start(); System.out.println( t1.getName() + " before interupt:" + t1.isInterrupted() + " is alive=" + t1.isAlive()); System.out.println( t2.getName() + " before interupt:" + t2.isInterrupted() + " is alive=" + t2.isAlive()); TimeUnit.SECONDS.sleep(1); t1.interrupt(); t2.interrupt(); TimeUnit.SECONDS.sleep(1); System.out.println( t1.getName() + " after interupt:" + t1.isInterrupted() + " is alive=" + t1.isAlive()); System.out.println( t2.getName() + " after interupt:" + t2.isInterrupted() + " is alive=" + t2.isAlive()); }
/** * Parse an XML document from a location identified by an URI reference. If the URI contains a * fragment identifier (see section 4.1 in ), the behavior is not defined by this specification. */ public Document parseURI(String uri) throws LSException { // If DOMParser insstance is already busy parsing another document when this // method is called, then raise INVALID_STATE_ERR according to DOM L3 LS spec if (fBusy) { String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null); throw new DOMException(DOMException.INVALID_STATE_ERR, msg); } XMLInputSource source = new XMLInputSource(null, uri, null, false); try { currentThread = Thread.currentThread(); fBusy = true; parse(source); fBusy = false; if (abortNow && currentThread.isInterrupted()) { // reset interrupt state abortNow = false; Thread.interrupted(); } } catch (Exception e) { fBusy = false; if (abortNow && currentThread.isInterrupted()) { Thread.interrupted(); } if (abortNow) { abortNow = false; restoreHandlers(); return null; } // Consume this exception if the user // issued an interrupt or an abort. if (e != Abort.INSTANCE) { if (!(e instanceof XMLParseException) && fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl(); error.fException = e; error.fMessage = e.getMessage(); error.fSeverity = DOMError.SEVERITY_FATAL_ERROR; fErrorHandler.getErrorHandler().handleError(error); } if (DEBUG) { e.printStackTrace(); } throw (LSException) DOMUtil.createLSException(LSException.PARSE_ERR, e).fillInStackTrace(); } } Document doc = getDocument(); dropDocumentReferences(); return doc; }
/** Parse an XML document from a resource identified by an <code>LSInput</code>. */ public Document parse(LSInput is) throws LSException { // need to wrap the LSInput with an XMLInputSource XMLInputSource xmlInputSource = dom2xmlInputSource(is); if (fBusy) { String msg = DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "INVALID_STATE_ERR", null); throw new DOMException(DOMException.INVALID_STATE_ERR, msg); } try { currentThread = Thread.currentThread(); fBusy = true; parse(xmlInputSource); fBusy = false; if (abortNow && currentThread.isInterrupted()) { // reset interrupt state abortNow = false; Thread.interrupted(); } } catch (Exception e) { fBusy = false; if (abortNow && currentThread.isInterrupted()) { Thread.interrupted(); } if (abortNow) { abortNow = false; restoreHandlers(); return null; } // Consume this exception if the user // issued an interrupt or an abort. if (e != Abort.INSTANCE) { if (!(e instanceof XMLParseException) && fErrorHandler != null) { DOMErrorImpl error = new DOMErrorImpl(); error.fException = e; error.fMessage = e.getMessage(); error.fSeverity = DOMError.SEVERITY_FATAL_ERROR; fErrorHandler.getErrorHandler().handleError(error); } if (DEBUG) { e.printStackTrace(); } throw (LSException) DOMUtil.createLSException(LSException.PARSE_ERR, e).fillInStackTrace(); } } Document doc = getDocument(); dropDocumentReferences(); return doc; }
public SearcherResult findRuleMatchesOnIndex(PatternRule rule, Language language) throws IOException, UnsupportedPatternRuleException { // it seems wasteful to re-open the index every time, but I had strange problems (OOM, Array out // of bounds, ...) // when not doing so... open(); try { final PatternRuleQueryBuilder patternRuleQueryBuilder = new PatternRuleQueryBuilder(language); final Query query = patternRuleQueryBuilder.buildRelaxedQuery(rule); if (query == null) { throw new NullPointerException("Cannot search on null query for rule: " + rule.getId()); } final SearchRunnable runnable = new SearchRunnable(indexSearcher, query, language, rule); final Thread searchThread = new Thread(runnable); searchThread.start(); try { // using a TimeLimitingCollector is not enough, as it doesn't cover all time required to // search for a complicated regex, so interrupt the whole thread instead: if (limitSearch) { // FIXME: I don't know a simpler way to achieve this searchThread.join(maxSearchTimeMillis); } else { searchThread.join(Integer.MAX_VALUE); } searchThread.interrupt(); } catch (InterruptedException e) { throw new RuntimeException("Search thread got interrupted for query " + query, e); } if (searchThread.isInterrupted()) { throw new SearchTimeoutException( "Search timeout of " + maxSearchTimeMillis + "ms reached for query " + query); } final Exception exception = runnable.getException(); if (exception != null) { if (exception instanceof SearchTimeoutException) { throw (SearchTimeoutException) exception; } throw new RuntimeException( "Exception during search for query " + query + " on rule " + rule.getId(), exception); } final List<MatchingSentence> matchingSentences = runnable.getMatchingSentences(); final int sentencesChecked = getSentenceCheckCount(query, indexSearcher); final SearcherResult searcherResult = new SearcherResult(matchingSentences, sentencesChecked, query); searcherResult.setHasTooManyLuceneMatches(runnable.hasTooManyLuceneMatches()); searcherResult.setLuceneMatchCount(runnable.getLuceneMatchCount()); if (runnable.hasTooManyLuceneMatches()) { // more potential matches than we can check in an acceptable time :-( searcherResult.setDocCount(maxHits); } else { searcherResult.setDocCount(getDocCount(indexSearcher)); } // TODO: the search itself could also timeout, don't just ignore that: // searcherResult.setResultIsTimeLimited(limitedTopDocs.resultIsTimeLimited); return searcherResult; } finally { close(); } }
@Test public void testThreadDetails() { final AtomicReference<Thread> threadRef = new AtomicReference<Thread>(); SingleThreadEventExecutor executor = new SingleThreadEventExecutor(null, Executors.newCachedThreadPool(), false) { @Override protected void run() { threadRef.set(Thread.currentThread()); while (!confirmShutdown()) { Runnable task = takeTask(); if (task != null) { task.run(); } } } }; ThreadProperties threadProperties = executor.threadProperties(); Assert.assertSame(threadProperties, executor.threadProperties()); Thread thread = threadRef.get(); Assert.assertEquals(thread.getId(), threadProperties.id()); Assert.assertEquals(thread.getName(), threadProperties.name()); Assert.assertEquals(thread.getPriority(), threadProperties.priority()); Assert.assertEquals(thread.getState(), threadProperties.state()); Assert.assertEquals(thread.isAlive(), threadProperties.isAlive()); Assert.assertEquals(thread.isDaemon(), threadProperties.isDaemon()); Assert.assertEquals(thread.isInterrupted(), threadProperties.isInterrupted()); Assert.assertTrue(threadProperties.stackTrace().length > 0); executor.shutdownGracefully(); }
@Override public void stop() { while (!sqlt.isInterrupted()) { sqlt.interrupt(); } System.out.println("MySQL monitor stopped!"); }
/** * Spins/yields/blocks until node s is matched or caller gives up. * * @param s the waiting node * @param pred the predecessor of s, or s itself if it has no predecessor, or null if unknown (the * null case does not occur in any current calls but may in possible future extensions) * @param e the comparison value for checking match * @param timed if true, wait only until timeout elapses * @param nanos timeout in nanosecs, used only if timed is true * @return matched item, or e if unmatched on interrupt or timeout */ private E awaitMatch(Node s, Node pred, E e, boolean timed, long nanos) { final long deadline = timed ? System.nanoTime() + nanos : 0L; Thread w = Thread.currentThread(); int spins = -1; // initialized after first item and cancel checks ThreadLocalRandom randomYields = null; // bound if needed for (; ; ) { Object item = s.item; if (item != e) { // matched // assert item != s; s.forgetContents(); // avoid garbage return LinkedTransferQueue.<E>cast(item); } if ((w.isInterrupted() || (timed && nanos <= 0)) && s.casItem(e, FORGOTTEN)) { // cancel unsplice(pred, s); return e; } if (spins < 0) { // establish spins at/near front if ((spins = spinsFor(pred, s.isData)) > 0) randomYields = ThreadLocalRandom.current(); } else if (spins > 0) { // spin --spins; if (randomYields.nextInt(CHAINED_SPINS) == 0) Thread.yield(); // occasionally yield } else if (s.waiter == null) { s.waiter = w; // request unpark then recheck } else if (timed) { nanos = deadline - System.nanoTime(); if (nanos > 0L) LockSupport.parkNanos(this, nanos); } else { LockSupport.park(this); } } }
public void stopServer() throws Exception { if (!thread.isInterrupted()) thread.interrupt(); while (thread.isAlive()) { Thread.sleep(250); } }
private void parse( final DataInputStream dis, final GenometryModel gmodel, final AnnotatedSeqGroup seq_group, final String default_type) throws IOException { String type = default_type; String bedType = null; boolean use_item_rgb = false; final Thread thread = Thread.currentThread(); final BufferedReader reader = new BufferedReader(new InputStreamReader(dis)); String line; while ((line = reader.readLine()) != null && !thread.isInterrupted()) { if (!line.startsWith("#")) { if (line.length() == 0) { continue; } if (line.startsWith("track")) { this.track_line_parser.parseTrackLine(line); TrackLineParser.createTrackStyle( this.track_line_parser.getCurrentTrackHash(), default_type, "bed"); type = this.track_line_parser.getCurrentTrackHash().get("name"); final String item_rgb_string = this.track_line_parser.getCurrentTrackHash().get("itemrgb"); use_item_rgb = "on".equalsIgnoreCase(item_rgb_string); bedType = this.track_line_parser.getCurrentTrackHash().get("type"); } else { if (line.startsWith("browser")) { continue; } this.parseLine(line, seq_group, gmodel, type, use_item_rgb, bedType); } } } }
private void runLogging() { final Thread currentThread = Thread.currentThread(); final ConsoleRowFormatter consoleRowFormatter = new ConsoleRowFormatter(); anythingLogged = false; try { while (!currentThread.isInterrupted()) { ConsoleRow row = outputQueue.take(); // subtract length of contained test string modifyCharacterCount(-row.getPayload().length()); try { // TODO add an explicit flush mechanism to ensure rows are on disk after a // given time? writer.append(consoleRowFormatter.toCombinedLogFileFormat(row)); anythingLogged = true; } catch (IOException e) { log.error(e); break; } } } catch (InterruptedException e) { log.debug("Background log writer interrupted"); } try { writer.close(); // TODO bad encapsulation; improve when reworking this class if (!anythingLogged) { logFile.delete(); } } catch (IOException e) { log.error(e); } }
@Override public synchronized void run() { try { while (!myThread.isInterrupted() && !exhausted) { synchronized (this) { while (!outstandingFillRequest) { wait(); } } fill(); outstandingFillRequest = false; } } catch (InterruptedException e) { // TODO: handle exception } catch (ThreadDeath e) { throw e; } catch (Throwable e) { exception = e; } finally { exhausted = true; synchronized (lockObject) { lockObject.notifyAll(); } try { in.close(); } catch (IOException e) { if (exception == null) { exception = e; } } in = null; } }
/** @param args */ public static void main(String[] args) throws Exception { final Thread thread = Thread.currentThread(); final CloneClient cloneClient = Patterns.newCloneClient("localhost", "localhost", "/client/"); Random rand = new Random(System.nanoTime()); while (!thread.isInterrupted()) { // Set random value, check it was stored String key = String.format("%s%d", "/client/", rand.nextInt(10000)); String value = String.format("%d", rand.nextInt(1000000)); log.info("Publishing update: {}={}", key, value); cloneClient.set(key, value, rand.nextInt(30)); Thread.sleep(1000); } Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { log.info("Stopping CloneClient..."); thread.interrupt(); try { thread.join(); } catch (InterruptedException ignored) { } log.info("CloneClient stopped"); } }); }
/** Stop the update thread. Also flush the remaining updates since we're stopping anyway */ public void stop() { running = false; if (thread != null && !thread.isInterrupted()) { thread.interrupt(); } }
@Override public void run() { Thread currentThread = Thread.currentThread(); while (!currentThread.isInterrupted()) { _selectorIntraband.selector.wakeup(); } }
@Override public void stop() { channel.disconnect(); session.disconnect(); while (!fmt.isInterrupted()) { fmt.interrupt(); } System.out.println("Flexiant cloud monitor stopped!"); }
@Override public void call(final Subscriber<? super T> subscriber) { final Realm realm = Realm.getInstance(context); thread = Thread.currentThread(); subscriber.add( Subscriptions.create( new Action0() { @Override public void call() { if (thread != null && !thread.isInterrupted()) { thread.interrupt(); } } })); boolean interrupted = false; boolean withError = false; T object = null; try { realm.beginTransaction(); object = get(realm); interrupted = thread.isInterrupted(); if (object != null && !interrupted) { realm.commitTransaction(); } else { realm.cancelTransaction(); } } catch (RuntimeException e) { realm.cancelTransaction(); subscriber.onError(new RealmException("Error during transaction.", e)); withError = true; } catch (Error e) { realm.cancelTransaction(); subscriber.onError(e); withError = true; } if (!interrupted && !withError) { subscriber.onNext(object); } try { realm.close(); } catch (RealmException ex) { subscriber.onError(ex); withError = true; } thread = null; if (!withError) { subscriber.onCompleted(); } if (interrupted) { Thread.currentThread().interrupt(); } }
/** * Irá forçar a parada dos downloads * * @return Retorna false se não encontrar nenhum download em andamento */ public boolean stopDownload() { if (threadList.isEmpty()) return false; // Faz loop nos threads e verifica se eles ainda estão ativos e força o fechamento do mesmo for (Thread tr : threadList) { if (!tr.isInterrupted() || tr.isAlive()) { tr.interrupt(); threadList.remove(tr); } } return true; }
public void stop() { if (recorderStarted) { if (recordingThread != null && recordingThread.isAlive() && !recordingThread.isInterrupted()) { recordingThread.interrupt(); } recorderStarted = false; } }
@Override public void run() { Thread currentThread = Thread.currentThread(); for (Map.Entry<String, InvalidationEventQueue> entry : invalidationMessageMap.entrySet()) { if (currentThread.isInterrupted()) { break; } InvalidationEventQueue invalidationMessageQueue = entry.getValue(); if (invalidationMessageQueue.size() > 0) { flushInvalidationMessages(entry.getKey(), invalidationMessageQueue); } } }
/** * Called by thread which was parked after it resumes. Caller is responsible for removing node * from queue if return value is 0. * * @return -1 if interrupted, 0 if not signaled, 1 if signaled */ final int resumed(WaitQueue queue) { Thread thread = mWaiter; if (thread == null) { remove(queue); return 1; } if (thread.isInterrupted()) { Thread.interrupted(); remove(queue); return -1; } return 0; }
/** * Creates all the necessary sudokus. Returns <code>false</code> if interrupted. * * @return */ private boolean createSudokus() { int anzPuzzles = 0; for (int i = 0; i < numberTextFields.length; i++) { anzPuzzles += getNumberOfPuzzles(i); } if (anzPuzzles == 0) { // nothing to do return false; } sudokus = new Sudoku2[anzPuzzles]; candidates = new boolean[anzPuzzles]; int index = 0; for (int i = 0; i < numberTextFields.length; i++) { DifficultyLevel actDiffLevel = Options.getInstance().getDifficultyLevel(levelComboBoxes[i].getSelectedIndex() + 1); GameMode actGameMode = null; boolean withCandidates = candCheckBoxes[i].isSelected(); switch (modeComboBoxes[i].getSelectedIndex()) { case 0: actGameMode = GameMode.PLAYING; break; case 1: actGameMode = GameMode.LEARNING; break; case 2: actGameMode = GameMode.PRACTISING; break; } for (int j = 0; j < getNumberOfPuzzles(i); j++) { sudokus[index] = getSudoku(actDiffLevel, actGameMode); if (sudokus[index] == null || thread.isInterrupted()) { return false; } candidates[index] = withCandidates; // put puzzle in history Options.getInstance().addSudokuToHistory(sudokus[index]); index++; // update progress bar setPercentage((int) Math.round(index * 100.0 / anzPuzzles)); EventQueue.invokeLater( new Runnable() { @Override public void run() { setProgress(); } }); } } return true; }
/** * Loads a folder. This method should only be used by the loader thread. Otherwise this method is * a no-op. * * @param folder The folder to load. */ public void loadFolder(final File folder) { final Thread t = Thread.currentThread(); if (t != iniLoader || t.isInterrupted()) return; synchronized (chunks) { chunks.clear(); } MapReader.clearCache(); final File[] files = folder.listFiles( new FileFilter() { @Override public boolean accept(final File f) { return f.isFile() && f.getName().endsWith(RegionFile.ANVIL_EXTENSION); } }); Arrays.sort( files, new Comparator<File>() { @Override public int compare(final File left, final File right) { final String leftStr = left.getName().replace("-", ""); final String rightStr = right.getName().replace("-", ""); return leftStr.compareTo(rightStr); } }); for (final File f : files) { final MapReader r = MapReader.getForFile(f); final List<Pair> chunkList = r.getChunks(); for (final Pair p : chunkList) { if (t != iniLoader || t.isInterrupted()) return; final Chunk chunk = new Chunk(r.read(p.x, p.z), f, p); unloadChunk(chunk); } user.somethingChanged(); } }
public void run() { Thread thread = currentThread(); if (thread.isInterrupted()) System.out.println("Нить прервана"); while (true) { System.out.println(this); if (--countDownIndex == 0) return; try { sleep(10); } catch (InterruptedException e) { } // add sleep here - добавь sleep тут } }
public static void main(String[] args) { // sleepThread 不停的尝试睡眠 Thread sleepThread = new Thread(new SleepRunner(), "SleepThread"); sleepThread.setDaemon(true); // busyThread 不停的运行 Thread busyThread = new Thread(new BusyRunner(), "BusyThread"); busyThread.setDaemon(true); busyThread.start(); // 休息5秒,让sleepThread 和 busyThread 充分运行 SleepUtils.second(5); sleepThread.interrupt(); busyThread.interrupt(); System.out.println( "SleepThread interrupted is " + sleepThread.isInterrupted()); // false,InterruptException 会清除中断标识位 System.out.println("BusyThread interrupted is " + busyThread.isInterrupted()); // true // 防止sleepThread 和busyThread 立刻退出 SleepUtils.second(2); }
/** Print diagnostic information about currently running threads at warn level. */ public void threadGroupList() { Thread[] threads = new Thread[_threads.activeCount()]; _threads.enumerate(threads); for (Thread thread : threads) { LOGGER.warn( "Thread: {} [{}{}{}] ({}) {}", thread.getName(), (thread.isAlive() ? "A" : "-"), (thread.isDaemon() ? "D" : "-"), (thread.isInterrupted() ? "I" : "-"), thread.getPriority(), thread.getState()); for (StackTraceElement s : thread.getStackTrace()) { LOGGER.warn(" {}", s); } } }
/** * Spins/blocks until node s is matched by a fulfill operation. * * @param s the waiting node * @param timed true if timed wait * @param nanos timeout value * @return matched node, or s if cancelled */ SNode awaitFulfill(SNode s, boolean timed, long nanos) { /* * When a node/thread is about to block, it sets its waiter * field and then rechecks state at least one more time * before actually parking, thus covering race vs * fulfiller noticing that waiter is non-null so should be * woken. * * When invoked by nodes that appear at the point of call * to be at the head of the stack, calls to park are * preceded by spins to avoid blocking when producers and * consumers are arriving very close in time. This can * happen enough to bother only on multiprocessors. * * The order of checks for returning out of main loop * reflects fact that interrupts have precedence over * normal returns, which have precedence over * timeouts. (So, on timeout, one last check for match is * done before giving up.) Except that calls from untimed * SynchronousQueue.{poll/offer} don't check interrupts * and don't wait at all, so are trapped in transfer * method rather than calling awaitFulfill. */ long lastTime = timed ? System.nanoTime() : 0; Thread w = Thread.currentThread(); SNode h = head; int spins = (shouldSpin(s) ? (timed ? maxTimedSpins : maxUntimedSpins) : 0); for (; ; ) { if (w.isInterrupted()) s.tryCancel(); SNode m = s.match; if (m != null) return m; if (timed) { long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) { s.tryCancel(); continue; } } if (spins > 0) spins = shouldSpin(s) ? (spins - 1) : 0; else if (s.waiter == null) s.waiter = w; // establish waiter so can park next iter else if (!timed) LockSupport.park(this); else if (nanos > spinForTimeoutThreshold) LockSupport.parkNanos(this, nanos); } }
@Override public void run() { while (!mThread.isInterrupted()) { try { Pair pair = mQueue.poll(1, TimeUnit.SECONDS); if (pair != null) { try { processPacket(pair.mMessage, pair.mTransmitter); } catch (IOException e) { e.printStackTrace(); } } } catch (InterruptedException e) { break; } } }
private void fill() throws IOException { for (int i = (activeBuffer + 1) % counts.length; i != activeBuffer && !myThread.isInterrupted(); i = (i + 1) % counts.length) { if (counts[i] == 0) { int thisCount = fillOneBuffer(i); if (thisCount == -1) { exhausted = true; Thread.currentThread().interrupt(); } } else { synchronized (lockObject) { lockObject.notifyAll(); } } } }
@Override public Object eval(final Reader reader) throws ScriptException { setup(); try { final Object filename = get(ScriptEngine.FILENAME); if (filename != null) put("clojure.core.*file*", filename); final Thread thread = Thread.currentThread(); Object finalResult = null; while (!thread.isInterrupted()) { final Object form = LispReader.read(new PushbackReader(reader), false, this, false); if (form == this) break; finalResult = Compiler.eval(form); } return finalResult; } catch (final Exception e) { throw new ScriptException(e); } }