@Override public boolean onTouchEvent(MotionEvent event) { xPosition = (int) event.getX(); yPosition = (int) event.getY(); double abs = Math.sqrt( (xPosition - centerX) * (xPosition - centerX) + (yPosition - centerY) * (yPosition - centerY)); if (abs > joystickRadius) { xPosition = (int) ((xPosition - centerX) * joystickRadius / abs + centerX); yPosition = (int) ((yPosition - centerY) * joystickRadius / abs + centerY); } invalidate(); if (event.getAction() == MotionEvent.ACTION_UP) { xPosition = (int) centerX; yPosition = (int) centerY; Log.i(logTag, "ACTION_UP: " + xPosition + ", " + yPosition); thread.interrupt(); onJoystickMoveListener.onValueChanged(getAngle(), getPower(), getDirection()); } if (onJoystickMoveListener != null && event.getAction() == MotionEvent.ACTION_DOWN) { if (thread != null && thread.isAlive()) { thread.interrupt(); } thread = new Thread(this); thread.start(); onJoystickMoveListener.onValueChanged(getAngle(), getPower(), getDirection()); Log.i(logTag, "ACTION_DOWN"); } return true; }
private synchronized void closeConnection() { stopBuffersThreads(); if (connectedThread != null) { connectedThread.cancel(); connectedThread.interrupt(); connectedThread = null; } boolean isConnected; synchronized (isConnectedLock) { isConnected = this.isConnected; this.isConnected = false; } if (callbacksTimeout != null) callbacksTimeout.stopTimer(); if (exitingCallbacksThread != null && exitingCallbacksThread.isAlive()) exitingCallbacksThread.interrupt(); if (enteringCallbacksThread != null && enteringCallbacksThread.isAlive()) enteringCallbacksThread.interrupt(); queuedFrames.clear(); synchronized (arduinoCallbacksLock) { isInACallback = false; } if (isConnected) { Log.d("Device " + this.name + ": Device disconnected."); onDisconnect(); } }
private synchronized void abort() { if (mode == ABORT_MODE) { return; } mode = ABORT_MODE; try { log.info("Aborting operation"); if (remote_sock != null) { remote_sock.close(); } if (sock != null) { sock.close(); } if (relayServer != null) { relayServer.stop(); } if (ss != null) { ss.close(); } if (pipe_thread1 != null) { pipe_thread1.interrupt(); } if (pipe_thread2 != null) { pipe_thread2.interrupt(); } } catch (final IOException ioe) { } }
private static double executeWithDisruptorPipeline(int numConsumers) { CountDownLatch cdl = new CountDownLatch(numConsumers); List<Consumer> consumers = createConsumers(numConsumers, null, cdl, SIMULATE_PROCESSING); MessagePipeDisruptorImpl<Carbon> pipeline = new MessagePipeDisruptorImpl<Carbon>( QUEUE_SIZE, AtomEvent.EVENT_FACTORY, new YieldingWaitStrategy(), consumers); Producer producer = new Producer(pipeline, NUM_MANU_UNITS); Thread producerThread = new Thread(producer); producerThread.start(); long startTime = System.currentTimeMillis(); try { cdl.await(); printStatistics(consumers); long endTime = System.currentTimeMillis(); out.println("Took " + (endTime - startTime) + " ms"); pipeline.halt(); producerThread.interrupt(); while (producerThread.isAlive()) { out.println("Interrupting producer"); producerThread.interrupt(); Thread.sleep(300); } ; return endTime - startTime; } catch (InterruptedException e) { e.printStackTrace(); return Double.POSITIVE_INFINITY; } }
/** * 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()); } }
public void waitInternal(boolean interrupt) { if (queueListener.get() == null) { return; } if (isCurrentThread()) { return; } long MAX_TIMEOUT = 1000 * 10; long start = System.currentTimeMillis(); while (queueListener.get().isRunning()) { try { TimeUnit.MILLISECONDS.sleep(100); Thread thread = queueListener.get().getThread(); if (interrupt) { if (thread != null) { thread.interrupt(); } } else if (System.currentTimeMillis() - start > MAX_TIMEOUT) { if (thread != null) { String msg = "Waited for " + MAX_TIMEOUT + "ms, will now interrupt the thread"; log.warn(msg); thread.interrupt(); throw new RuntimeException(msg); } } } catch (InterruptedException e) { log.trace("Got Interrupted while waiting for tasks.", e); } } }
/** * Closes all the threads and frees the resources This is the last method to call before closing * the application * * @param sync If it is true wait the termination of the threads before returning */ public void close(boolean sync) { terminateThread = true; keysDeleter.close(); closed = true; if (tableUpdater != null) { tableUpdater.interrupt(); if (sync) { try { // We do not want to wait forever.. tableUpdater.join(10000); if (tableUpdater.isAlive()) { System.err.println("LogEntryTableModelBase.TableUpdater thread still alive!"); } } catch (InterruptedException ie) { } } } clearAll(); if (keysDeleterThread != null) { keysDeleterThread.interrupt(); if (sync) { try { // We do not want to wait forever.. keysDeleterThread.join(10000); if (keysDeleterThread.isAlive()) { System.err.println("LogEntryTableModelBase.KeysDeleter thread still alive!"); } } catch (InterruptedException ie) { } } } }
/** * @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()); }
private void shutdown() { writerRunner.shutdown(); readerRunner.shutdown(); if (writerThread.isAlive()) { writerThread.interrupt(); } if (readerThread.isAlive()) { readerThread.interrupt(); } }
/** Run the test for the queue parameter. */ public static SynchronizedQueueResult testQueue(QueueAdapter<Integer> queue) { try { mQueue = queue; // Please make sure to keep all the "TODO" comments in the // code below to make it easy for peer reviewers to find // them. // TODO - you fill in here to replace the null // initialization below to create two Java Threads, one // that's passed the producerRunnable and the other that's // passed the consumerRunnable. Thread consumer = new Thread(consumerRunnable); Thread producer = new Thread(producerRunnable); // TODO - you fill in here to start the threads. More // interesting results will occur if you start the // consumer first. producer.start(); consumer.start(); // Give the Threads a chance to run before interrupting // them. Thread.sleep(100); // TODO - you fill in here to interrupt the threads. producer.interrupt(); consumer.interrupt(); // TODO - you fill in here to wait for the threads to // exit. consumer.join(); producer.join(); ; // Do some sanity checking to see if the Threads work as // expected. if (consumer == null || producer == null) return SynchronizedQueueResult.THREADS_NEVER_CREATED; else if (consumer.isAlive() || producer.isAlive()) return SynchronizedQueueResult.JOIN_NEVER_CALLED; else if (mConsumerCounter == 0 || mProducerCounter == 0) return SynchronizedQueueResult.THREADS_NEVER_RAN; else if (mConsumerCounter == mMaxIterations || mProducerCounter == mMaxIterations) return SynchronizedQueueResult.THREADS_NEVER_INTERUPTED; else if (mConsumerCounter == FAILURE_OCCURRED || mProducerCounter == FAILURE_OCCURRED) return SynchronizedQueueResult.THREADS_THREW_EXCEPTION; else if (mConsumerCounter == TIMEOUT_OCCURRED || mProducerCounter == TIMEOUT_OCCURRED) return SynchronizedQueueResult.THREADS_TIMEDOUT; else return SynchronizedQueueResult.RAN_PROPERLY; } catch (Exception e) { return SynchronizedQueueResult.TESTING_LOGIC_THREW_EXCEPTION; } }
@Override public void run() { Thread sendingThread = null; Thread loggingThread = null; try { final long connectionTime = System.currentTimeMillis(); mConnectionTime.set(connectionTime); reportConnect(connectionTime); // Launch the 'Sending' thread mLogger.logInfo(TAG, "Starting sender thread."); sendingThread = new Thread(mSendingTask, "MavLinkConnection-Sending Thread"); sendingThread.start(); // Launch the 'Logging' thread mLogger.logInfo(TAG, "Starting logging thread."); loggingThread = new Thread(mLoggingTask, "MavLinkConnection-Logging Thread"); loggingThread.start(); final Parser parser = new Parser(); parser.stats.mavlinkResetStats(); final byte[] readBuffer = new byte[READ_BUFFER_SIZE]; while (mConnectionStatus.get() == MAVLINK_CONNECTED) { int bufferSize = readDataBlock(readBuffer); handleData(parser, bufferSize, readBuffer); } } catch (IOException e) { // Ignore errors while shutting down if (mConnectionStatus.get() != MAVLINK_DISCONNECTED) { reportComError(e.getMessage()); mLogger.logErr(TAG, e); } } finally { if (sendingThread != null && sendingThread.isAlive()) { sendingThread.interrupt(); } if (loggingThread != null && loggingThread.isAlive()) { loggingThread.interrupt(); } disconnect(); mLogger.logInfo(TAG, "Exiting manager thread."); } }
public static void main(String[] args) { Bucket bucket = new Bucket(123); Thread consumerThread = new Thread(new Consumer(bucket)); Thread producerThread = new Thread(new Producer(bucket)); consumerThread.start(); producerThread.start(); try { Thread.sleep(1000); } catch (InterruptedException ignored) { } consumerThread.interrupt(); producerThread.interrupt(); try { consumerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } try { producerThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("all threads are stopped"); System.out.println(bucket); }
/** Chiude la connessione. Chiude il socket e ferma tutti i background threads. */ public void close() { boolean oldStatus = open; Log.d(TAG, "connection close requested"); if (requestThread != null) { requestThread .interrupt(); // nel Thread il metodo Thread.sleep() genera una InterruptedException } if (receiveThread != null) { receiveThread .interrupt(); // nel Thread il metodo Thread.sleep() genera una InterruptedException } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } open = false; fireStatusChanged(oldStatus, false); Log.d(TAG, "connection has been closed"); }
public void dispose() { try { _clientSocket.close(); } catch (Exception e) { // ignore } try { _deviceSocket.close(); } catch (Exception e) { // ignore } try { clientThread.interrupt(); } catch (Exception e) { // ignore } try { deviceThread.interrupt(); } catch (Exception e) { // ignore } _clientSocket = null; clientThread = null; _deviceSocket = null; deviceThread = null; clientServer = null; deviceServer = null; }
public static void main(String[] args) throws InterruptedException { Object lock = new Object(); RunEven runEven = new RunEven(); runEven.setLock(lock); Thread tEven = new Thread(runEven, "runEven"); /*Thread tOdd1 = new Thread( runEven); Thread tOdd2 = new Thread( runEven);*/ RunOdd runOdd = new RunOdd(); runOdd.setLock(lock); Thread tOdd = new Thread(runOdd, "runOdd"); // RunEven.getAnInt(1); // RunOdd.getAnInt(9); /*Thread tEven1 = new Thread( runOdd); Thread tEven2 = new Thread( runOdd); */ tEven.start(); // RunEven.getAnInt(4); // tEven1.start(); // tEven2.start(); // Thread.sleep(1000); tOdd.start(); // RunOdd.getAnInt(5); // tOdd1.start(); // tOdd2.start(); tEven.join(); System.out.println("All printing Done !! "); tEven.interrupt(); tOdd.interrupt(); }
public static void stopPCconectado() { try { t2.interrupt(); t.interrupt(); } catch (Exception e) { } }
/* (non-Javadoc) * @see ch.inf.vs.californium.network.connector.Connector#stop() */ @Override public synchronized void stop() { if (!running) return; running = false; senderThread.interrupt(); receiverThread.interrupt(); outgoing.clear(); }
public void stop() throws IOException { receiverThread.interrupt(); emitterThread.interrupt(); if (!socket.isClosed()) { socket.close(); } }
/** Stop the internal threads */ public void stop() { // Stop the Threads toReceive.interrupt(); toSend.interrupt(); // Disconnect from the service communicationsVPNConnection.close(); }
@Override public void destroy() { Thread thread = _pipeThread; if (thread != null) { thread.interrupt(); } thread = _adminShellThread; if (thread != null) { thread.interrupt(); } }
@Override public void onDestroy() { if (clientThread0 != null) { clientThread0.interrupt(); clientThread0 = null; } if (clientThread1 != null) { clientThread1.interrupt(); clientThread1 = null; } Log.d(tag, "Socket RaspberryPi onDestroy"); super.onDestroy(); }
@Test public void testNewSubNotBlockedByTimeoutTask() throws Exception { // Default config is 1s interval, 300s timeout. // Create a topic String testName = "AutoAckTopicTest.testNewSubNotBlockedByTimeoutTask"; TopicDeployment deployment = new TopicDeployment(); deployment.setDuplicatesAllowed(true); deployment.setDurableSend(false); deployment.setName(testName); manager.getTopicManager().deploy(deployment); // Create a consumer ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/topics/" + testName)); ClientResponse<?> response = request.head(); response.releaseConnection(); Assert.assertEquals(200, response.getStatus()); Link sender = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "create"); Link subscriptions = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), response, "pull-subscriptions"); // Create the pull-subscription itself. ClientResponse<?> res = subscriptions.request().post(); res.releaseConnection(); Assert.assertEquals(201, res.getStatus()); Link sub1 = res.getLocationLink(); Assert.assertNotNull(sub1); Link consumeNext1 = getLinkByTitle(manager.getTopicManager().getLinkStrategy(), res, "consume-next"); Assert.assertNotNull(consumeNext1); // Pull on the topic for 8s (long enoguh to guarantee the rest of the test // will pass/fail due to the timeouttask + test operations) AcceptWaitListener awlistener = new AcceptWaitListener(consumeNext1.getHref()); Thread t = new Thread(awlistener); t.start(); // Wait 2 seconds to ensure a new TimeoutTask is running concurrently. Thread.sleep(2000); // Attempt to create a new pull-subscription. Validate that it takes no longer than 2 seconds // (it should take like 20ms, but give it a relatively huge amount of leeway) NewPullSubscriber nps = new NewPullSubscriber(subscriptions.getHref()); Thread npsThread = new Thread(nps); npsThread.start(); Thread.sleep(2000); Assert.assertTrue("NewPullSubscriber did not finish in 2 seconds!", nps.isFinished()); Assert.assertFalse("AcceptWaitListener failed to open connection!", awlistener.isFailed()); Assert.assertFalse("NewPullSubscriber failed to open new subscription!", nps.isFailed()); npsThread.interrupt(); t.interrupt(); }
public static void main(String[] args) throws Exception { int counter = 0; while (true) { Thread outThread = null; Thread errThread = null; try { // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange // *** start slave ServerSocket commSocket = new ServerSocket(0); int commPort = commSocket.getLocalPort(); System.out.println("commPort = " + commPort); // org.pitest.mutationtest.execute.MutationTestProcess#start // - org.pitest.util.CommunicationThread#start FutureTask<Integer> commFuture = createFuture(commSocket); // - org.pitest.util.WrappingProcess#start // - org.pitest.util.JavaProcess#launch Process slaveProcess = startSlaveProcess(commPort); outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout"); errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr"); outThread.start(); errThread.start(); // *** wait for slave to die // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie // - org.pitest.util.CommunicationThread#waitToFinish System.out.println("waitToFinish"); Integer controlReturned = commFuture.get(); System.out.println("controlReturned = " + controlReturned); // NOTE: the following won't get called if commFuture.get() fails! // - org.pitest.util.JavaProcess#destroy outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop slaveProcess.destroy(); } catch (Exception e) { e.printStackTrace(System.out); } // test: the threads should exit eventually outThread.join(); errThread.join(); counter++; System.out.println("try " + counter + ": stdout and stderr threads exited normally"); } }
public static void main(String[] args) { final ObjectDemo demo = new ObjectDemo(); Runnable runA = new Runnable() { public void run() { try { String item = demo.removeElement(); System.out.println("" + item); } catch (InterruptedException ix) { System.out.println("Interrupted Exception!"); } catch (Exception x) { System.out.println("Exception thrown."); } } }; Runnable runB = new Runnable() { // run adds an element in the list and starts the loop public void run() { demo.addElement("Hello!"); } }; try { Thread threadA1 = new Thread(runA, "A"); threadA1.start(); Thread.sleep(500); Thread threadA2 = new Thread(runA, "B"); threadA2.start(); Thread.sleep(500); Thread threadB = new Thread(runB, "C"); threadB.start(); Thread.sleep(1000); threadA1.interrupt(); threadA2.interrupt(); } catch (InterruptedException x) { } }
/** * A new method that interrupts the worker thread. Call this method to force the worker to stop * what it's doing. */ public void interrupt() { Thread t = threadVar.get(); if (t != null) { t.interrupt(); } threadVar.clear(); }
protected void cancelThread() { if (thread != null) { thread.interrupt(); } mHandler.removeCallbacks(r); hiddenProgressToolBar(); }
/** {@inheritDoc} */ @SuppressWarnings("deprecation") public void stop() { this.isRunning_ = false; if (this.isListening_ == false) { try { // 通信用ポートBind待ち状態のために、割り込みを行う Thread acceptThread = this.acceptThread_; if (acceptThread != null) { acceptThread.interrupt(); } } catch (Exception ex) { LOGGER.warn(ex); } } if (this.isListening_) { // 待ち受けソケットを閉じることにより、accept()でSocketExceptionが // 発生し、待ち受けスレッドが停止する。 if (this.objServerSocket_ != null) { try { this.objServerSocket_.close(); } catch (Exception ex) { LOGGER.warn(ex); } } this.isListening_ = false; } }
public synchronized void stop() { running = false; if (runThread != null) { runThread.interrupt(); } runThread = null; }
/** * Closes all connected clients sockets, then closes the underlying ServerSocketChannel, * effectively killing the server socket selectorthread, freeing the port the server was bound to * and stops all internal workerthreads. * * <p>If this method is called before the server is started it will never start. * * @param timeout Specifies how many milliseconds shall pass between initiating the close * handshakes with the connected clients and closing the servers socket channel. * @throws IOException When {@link ServerSocketChannel}.close throws an IOException * @throws InterruptedException */ public void stop(int timeout) throws IOException, InterruptedException { if (!isclosed.compareAndSet(false, true)) { return; } synchronized (connections) { for (WebSocket ws : connections) { ws.close(CloseFrame.GOING_AWAY); } } synchronized (this) { if (selectorthread != null) { if (Thread.currentThread() != selectorthread) {} if (selectorthread != Thread.currentThread()) { selectorthread.interrupt(); selectorthread.join(); } } if (decoders != null) { for (WebSocketWorker w : decoders) { w.interrupt(); } } if (server != null) { server.close(); } } }
/** Stop montioring the Launchpad controls. */ public void Stop() { Util.consoleLog(); if (monitorLaunchPadThread != null) monitorLaunchPadThread.interrupt(); monitorLaunchPadThread = null; }