private void shutdown() { writerRunner.shutdown(); readerRunner.shutdown(); if (writerThread.isAlive()) { writerThread.interrupt(); } if (readerThread.isAlive()) { readerThread.interrupt(); } }
// 检查任务是否结束 private boolean isTaskFinished() { // 如果reader 或 writer没有完成工作,那么直接返回工作没有完成 if (readerThread.isAlive() || writerThread.isAlive()) { return false; } if (taskCommunication == null || !taskCommunication.isFinished()) { return false; } return true; }
@Test public void concurrent_first_key() { DB db = DBMaker.memoryDB().transactionDisable().make(); final BTreeMap m = db.treeMap("name"); // fill final int c = 1000000 * TT.scale(); for (int i = 0; i <= c; i++) { m.put(i, i); } Thread t = new Thread() { @Override public void run() { for (int i = 0; i <= c; i++) { m.remove(c); } } }; t.run(); while (t.isAlive()) { assertNotNull(m.firstKey()); } }
/// The watcher thread - from the Runnable interface. // This has to be pretty anal to avoid monitor lockup, lost // threads, etc. public synchronized void run() { Thread me = Thread.currentThread(); me.setPriority(Thread.MAX_PRIORITY); ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); startTimeInNs = threadMXBean.getCurrentThreadCpuTime(); if (enabled.get()) { do { loop.set(false); try { wait(millis); } catch (InterruptedException e) { } } while (enabled.get() && loop.get()); } if (enabled.get() && targetThread.isAlive()) { isDoneRunning.set(true); printThread(); if (kill) { logger.warn( "Trying to kill thread with id:" + targetThread.getId() + " but did not as it can cause deadlocks etc."); // targetThread.interrupt(); // targetThread.stop(); //Never kill thread - it can cause other problems } done(); isDoneRunning.set(false); } }
/** compareAndSet in one thread enables another waiting for value to succeed */ public void testCompareAndSetInMultipleThreads() throws Exception { x = one; final AtomicReferenceFieldUpdater<AtomicReferenceFieldUpdaterTest, Integer> a; try { a = AtomicReferenceFieldUpdater.newUpdater( AtomicReferenceFieldUpdaterTest.class, Integer.class, "x"); } catch (RuntimeException ok) { return; } Thread t = new Thread( new CheckedRunnable() { public void realRun() { while (!a.compareAndSet(AtomicReferenceFieldUpdaterTest.this, two, three)) Thread.yield(); } }); t.start(); assertTrue(a.compareAndSet(this, one, two)); t.join(LONG_DELAY_MS); assertFalse(t.isAlive()); assertSame(a.get(this), three); }
private void timeoutIfStillRunning(Thread t) { if (t.isAlive()) { log.warn("Scenario timed out after " + scenarioTimeoutMillis + " millis, will interrupt"); stepProcessor.setInterruptingOnTimeout(true); t.interrupt(); // first try to interrupt to see if this can unblock/fail the scenario } }
@Override protected synchronized void onSizeChanged(int w, int h, int oldw, int oldh) { // update pixel conversion values PixelUtils.init(getContext()); // disable hardware acceleration if it's not explicitly supported // by the current Plot implementation. this check only applies to // honeycomb and later environments. if (Build.VERSION.SDK_INT >= 11) { if (!isHwAccelerationSupported() && isHardwareAccelerated()) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); } } // pingPong is only used in background rendering mode. if (renderMode == RenderMode.USE_BACKGROUND_THREAD) { pingPong.resize(h, w); } RectF cRect = new RectF(0, 0, w, h); RectF mRect = boxModel.getMarginatedRect(cRect); RectF pRect = boxModel.getPaddedRect(mRect); layout(new DisplayDimensions(cRect, mRect, pRect)); super.onSizeChanged(w, h, oldw, oldh); if (renderThread != null && !renderThread.isAlive()) { renderThread.start(); } }
private void killInterpreterIfStillRunning(Thread t) { if (t.isAlive()) { log.error( "Scenario did not respond to thread.kill() after timeout, will now kill the interpreter"); System.exit(1); } }
/** * This starts the layout thread, it does not run before this. Note this is a background check it * doesn't stop when done it just sleeps until it gets more work. */ public void start() { if (controller != null && !runner.isAlive() && !pauseState) { active = true; runner.start(); } }
/** * @param views Guaranteed to be non-null and to have >= 2 members, or else this thread would * not be started */ public synchronized void start(Map<Address, View> views) { if (thread == null || thread.isAlive()) { this.coords.clear(); // now remove all members which don't have us in their view, so RPCs won't block (e.g. // FLUSH) // https://jira.jboss.org/browse/JGRP-1061 sanitizeViews(views); // Add all different coordinators of the views into the hashmap and sets their members: Collection<Address> coordinators = Util.determineMergeCoords(views); for (Address coord : coordinators) { View view = views.get(coord); if (view != null) this.coords.put(coord, new ArrayList<Address>(view.getMembers())); } // For the merge participants which are not coordinator, we simply add them, and the // associated // membership list consists only of themselves Collection<Address> merge_participants = Util.determineMergeParticipants(views); merge_participants.removeAll(coordinators); for (Address merge_participant : merge_participants) { Collection<Address> tmp = new ArrayList<Address>(); tmp.add(merge_participant); coords.putIfAbsent(merge_participant, tmp); } thread = gms.getThreadFactory().newThread(this, "MergeTask"); thread.setDaemon(true); thread.start(); } }
public void getRepeaterIDCallBack(Map<String, Integer> repeaterids) throws Exception { log.info("getRepeaterIDCallBack"); if (screenshareflag) { if (!looThread.isAlive()) { looThread.start(); } Iterator<Entry<String, Integer>> iterator = repeaterids.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<java.lang.String, java.lang.Integer> entry = (Map.Entry<java.lang.String, java.lang.Integer>) iterator.next(); String remoteUserName = entry.getKey().substring(entry.getKey().indexOf("-") + 1); if (!remoteUserName.equals(DataUtil.getLoginInfo().getUsername())) { addToWaitList(remoteUserName, entry.getValue() + "", true); } } // DockingLayoutMeetingPanel panel = // DataUtil.getValue(DataUtil.Key.DockingLayoutMeetingPanel); // panel.getStartScreenShareMI().setEnabled(false); // panel.getStopScreenShareMI().setEnabled(true); MainFrame mainFrame = ViewManager.getComponent(MainFrame.class); mainFrame .getShareDesktopButton() .setText(StringUtil.getUIString("DockingLayoutMeetingPanel.stopScreenShareMI.text")); mainFrame.getShareDesktopButton().setEnabled(true); // screenshareflag = false; } }
/** Stops unicast and multicast receiver threads */ void stopThreads() { Thread tmp; // 1. Stop the multicast receiver thread if (mcast_receiver != null) { if (mcast_receiver.isAlive()) { tmp = mcast_receiver; mcast_receiver = null; closeMulticastSocket(); // will cause the multicast thread to terminate tmp.interrupt(); try { tmp.join(100); } catch (Exception e) { } tmp = null; } mcast_receiver = null; } // 2. Stop the unicast receiver thread if (ucast_receiver != null) { ucast_receiver.stop(); ucast_receiver = null; } // 3. Stop the in_packet_handler thread if (incoming_packet_handler != null) { incoming_packet_handler.stop(); } }
synchronized void start() { if (queue.closed()) queue.reset(); if (thread == null || !thread.isAlive()) { thread = getThreadFactory().newThread(this, "ViewHandler"); thread.setDaemon( false); // thread cannot terminate if we have tasks left, e.g. when we as coord leave thread.start(); } }
/** Spin-waits until sync.isQueued(t) becomes true. */ void waitForQueuedThread(AbstractQueuedLongSynchronizer sync, Thread t) { long startTime = System.nanoTime(); while (!sync.isQueued(t)) { if (millisElapsedSince(startTime) > LONG_DELAY_MS) throw new AssertionFailedError("timed out"); Thread.yield(); } assertTrue(t.isAlive()); }
private void stopThreadIfStillRunning(Thread t) { if (t.isAlive()) { log.error( "Scenario did not respond to interrupt after timeout, " + "will stop the interpreter thread and fail the tests"); t.stop(); // this will trigger a ThreadDeath exception which we should allow to propagate // and will terminate the interpreter } }
/* Add a new shutdown hook. Checks the shutdown state and the hook itself, * but does not do any security checks. */ static synchronized void add(Thread hook) { if (hooks == null) throw new IllegalStateException("Shutdown in progress"); if (hook.isAlive()) throw new IllegalArgumentException("Hook already running"); if (hooks.containsKey(hook)) throw new IllegalArgumentException("Hook previously registered"); hooks.put(hook, hook); }
public synchronized void handle(Socket socket) throws IOException { con = new Connection(socket); count = 0; if (thread == null || !thread.isAlive()) { thread = new Thread(runners, this); thread.start(); } else { notify(); } }
public void alert() { if (isUpnpDevice(uuid) && (monitor == null || !monitor.isAlive()) && !"STOPPED".equals(data.get("TransportState"))) { monitor(); } for (ActionListener l : listeners) { l.actionPerformed(event); } }
/** This initializes the runner thread. */ private void initThread() { if (runner == null || !runner.isAlive()) { runner = new Thread(this, "WeightedElasticLayoutThread"); stable = false; idleing = false; active = false; } else { System.err.println("WeightedElasticLayoutThread Error: Trying to Re-initialize thread"); } }
public void stop() { Thread tmp; if (thread != null && thread.isAlive()) { running = false; tmp = thread; thread = null; closeSocket(); // this will cause the thread to break out of its loop tmp.interrupt(); tmp = null; } thread = null; }
public boolean runMacroTool(String name) { for (int i = 0; i < nMacros; i++) { if (macroNames[i].startsWith(name)) { if (macroToolThread != null && macroToolThread.getName().indexOf(name) != -1 && macroToolThread.isAlive()) return false; // do nothing if this tool is already running MacroRunner mw = new MacroRunner(pgm, macroStarts[i], name, (String) null); macroToolThread = mw.getThread(); // IJ.log("runMacroTool: "+macroToolThread); return true; } } return false; }
static void test() throws Throwable { final ExecutorService executor = Executors.newCachedThreadPool(); final NotificationReceiver notifiee1 = new NotificationReceiver(); final NotificationReceiver notifiee2 = new NotificationReceiver(); final Collection<Callable<Object>> tasks = new ArrayList<Callable<Object>>(); tasks.add(new BlockingTask(notifiee1)); tasks.add(new BlockingTask(notifiee2)); tasks.add(new NonBlockingTask()); // start a thread to invoke the tasks Thread thread = new Thread() { public void run() { try { executor.invokeAll(tasks); } catch (RejectedExecutionException t) { /* OK */ } catch (Throwable t) { unexpected(t); } } }; thread.start(); // Wait until tasks begin execution notifiee1.waitForNotification(); notifiee2.waitForNotification(); // Now try to shutdown the executor service while tasks // are blocked. This should cause the tasks to be // interrupted. executor.shutdownNow(); if (!executor.awaitTermination(5, TimeUnit.SECONDS)) throw new Error("Executor stuck"); // Wait for the invocation thread to complete. thread.join(1000); if (thread.isAlive()) { thread.interrupt(); thread.join(1000); throw new Error("invokeAll stuck"); } }
/** This stops the layout if it's running, if it's not running it does nothing... */ public void stop() { if (runner.isAlive()) { try { active = false; if (idleing) { runner.interrupt(); } System.out.println( "Thread " + Thread.currentThread().getName() + " Ordering thread layout thread to stop."); runner.join(); initThread(); } catch (InterruptedException ex) { System.err.println("Layout Thread failed to stop"); Logger.getLogger(WeightedElasticLayout.class.getName()).log(Level.SEVERE, null, ex); } } }
/** * Ensure that the message loop thread is running. This method simply returns if the thread is * already running. It creates a new thread if the message thread is not running. This method does * not return until the message loop is initialized and ready for use. */ protected void ensureMessageLoopRunning() { synchronized (webViewUILock) { if (webViewUI == null || !webViewUI.isAlive()) { webViewMessageLoop = 0; // Create a new thread to run the web view message loop. webViewUI = new Thread("WebView UI") { public void run() { try { // Create a message loop in native code. This call must return // before any messages are sent to the WebView. webViewMessageLoop = WindowsWebViewJNI.newMessageLoop(); } catch (Throwable t) { webViewMessageLoop = -1; } finally { // Notify the outer thread that the message loop is ready or failed to start. synchronized (webViewUILock) { webViewUILock.notify(); } } // Process messages in native code until the message loop // is terminated. WindowsWebViewJNI.runMessageLoop(webViewMessageLoop); } }; webViewUI.start(); // Wait for the newly started thread to create the message loop. We cannot // safely use the WebView until the message loop has been initialized. while (webViewMessageLoop == 0) { try { webViewUILock.wait(1000); } catch (InterruptedException ignored) { } } } } }
/** Starts the unicast and multicast receiver threads */ void startThreads() throws Exception { if (ucast_receiver == null) { // start the listener thread of the ucast_recv_sock ucast_receiver = new UcastReceiver(); ucast_receiver.start(); if (Trace.trace) { Trace.info("UDP.startThreads()", "created unicast receiver thread"); } } if (ip_mcast) { if (mcast_receiver != null) { if (mcast_receiver.isAlive()) { if (Trace.trace) { Trace.info( "UDP.createThreads()", "did not create new multicastreceiver thread as existing " + "multicast receiver thread is still running"); } } else { mcast_receiver = null; // will be created just below... } } if (mcast_receiver == null) { mcast_receiver = new Thread(this, "UDP mcast receiver"); mcast_receiver.setPriority(Thread.MAX_PRIORITY); // needed ???? mcast_receiver.setDaemon(true); mcast_receiver.start(); } } if (use_outgoing_packet_handler) { outgoing_packet_handler.start(); } if (use_incoming_packet_handler) { incoming_packet_handler.start(); } }
public boolean isAlive() { return thread.isAlive(); }
public synchronized void stop() { Thread tmp = thread; if (thread != null && thread.isAlive()) tmp.interrupt(); thread = null; }
/** * Returns true if the layout is running, false if it's stopped or paused or ... * * @return true if running false otherwise. */ public boolean isRunning() { return runner.isAlive(); }
/** * Try to update an old block to a new block. If there are ongoing create threads running for the * old block, the threads will be returned without updating the block. * * @return ongoing create threads if there is any. Otherwise, return null. */ private synchronized List<Thread> tryUpdateBlock(Block oldblock, Block newblock) throws IOException { // check ongoing create threads final ActiveFile activefile = ongoingCreates.get(oldblock); if (activefile != null && !activefile.threads.isEmpty()) { // remove dead threads for (Iterator<Thread> i = activefile.threads.iterator(); i.hasNext(); ) { final Thread t = i.next(); if (!t.isAlive()) { i.remove(); } } // return living threads if (!activefile.threads.isEmpty()) { return new ArrayList<Thread>(activefile.threads); } } // No ongoing create threads is alive. Update block. File blockFile = findBlockFile(oldblock.getBlockId()); if (blockFile == null) { throw new IOException("Block " + oldblock + " does not exist."); } File oldMetaFile = findMetaFile(blockFile); long oldgs = parseGenerationStamp(blockFile, oldMetaFile); // rename meta file to a tmp file File tmpMetaFile = new File( oldMetaFile.getParent(), oldMetaFile.getName() + "_tmp" + newblock.getGenerationStamp()); if (!oldMetaFile.renameTo(tmpMetaFile)) { throw new IOException("Cannot rename block meta file to " + tmpMetaFile); } // update generation stamp if (oldgs > newblock.getGenerationStamp()) { throw new IOException( "Cannot update block (id=" + newblock.getBlockId() + ") generation stamp from " + oldgs + " to " + newblock.getGenerationStamp()); } // update length if (newblock.getNumBytes() > oldblock.getNumBytes()) { throw new IOException( "Cannot update block file (=" + blockFile + ") length from " + oldblock.getNumBytes() + " to " + newblock.getNumBytes()); } if (newblock.getNumBytes() < oldblock.getNumBytes()) { truncateBlock(blockFile, tmpMetaFile, oldblock.getNumBytes(), newblock.getNumBytes()); } // rename the tmp file to the new meta file (with new generation stamp) File newMetaFile = getMetaFile(blockFile, newblock); if (!tmpMetaFile.renameTo(newMetaFile)) { throw new IOException("Cannot rename tmp meta file to " + newMetaFile); } updateBlockMap(ongoingCreates, oldblock, newblock); updateBlockMap(volumeMap, oldblock, newblock); // paranoia! verify that the contents of the stored block // matches the block file on disk. validateBlockMetadata(newblock); return null; }
@Override public void stop() { if (myThread != null && myThread.isAlive()) { myThread.interrupt(); } }