This must run ON the IO thread
968751
@Override
    public void doFilterWrite(final long sessionId, final long sessionWrittenBytes, final WriteRequest writeRequest) throws
            Exception {
        Object message = writeRequest.getMessage();

        if (message instanceof IoBuffer) {
            ThreadGatewayStats stats = gatewayStats.get();
            stats.doFilterWrite((IoBuffer) message);
        }
    }
675934
@Override
	final public void run() {
		try {
			if(args.length>0) handleCommand(args);
			else runImpl();
			status="Done";
		} catch(IOException exception) {
			this.err.println(getName()+": "+exception.getMessage());
			status="IO Error: "+exception.getMessage();
			this.err.flush();
		} catch(SQLException exception) {
			this.err.println(getName()+": "+exception.getMessage());
			status="SQL Error: "+exception.getMessage();
			this.err.flush();
		} catch(ThreadDeath TD) {
			throw TD;
		} catch(Throwable T) {
			ErrorPrinter.printStackTraces(T, this.err);
			status="Error: "+T.toString();
			this.err.flush();
		} finally {
			if(Thread.currentThread()==thread) thread=null;
		}
	}
360103
@Override
  public void run() {
    synchronized (this) {
      started = true;
    }
    finished = false;

    final byte[] buf = new byte[bufferSize];

    try {
      int length;
      while (true) {
        waitForInput(is);

        if (finish || Thread.interrupted()) {
          break;
        }

        length = is.read(buf);
        if (length <= 0 || Thread.interrupted()) {
          break;
        }
        os.write(buf, 0, length);
        if (autoflush) {
          os.flush();
        }
        if (finish) { //NOSONAR
          break;
        }
      }
      // On completion, drain any available data (which might be the first data available for quick executions)
      if (finish) {
        while((length = is.available()) > 0) {
          if (Thread.interrupted()) {
            break;
          }
          length = is.read(buf, 0, Math.min(length, buf.length));
          if (length <= 0) {
            break;
          }
          os.write(buf, 0, length);
        }
      }
      os.flush();
    } catch (InterruptedException ie) {
      // likely PumpStreamHandler trying to stop us
    } catch (Exception e) {
      synchronized (this) {
        exception = e;
      }
    } finally {
      if (closeWhenExhausted) {
        Closeables.close(os);
      }
      finished = true;
      finish = false;
      synchronized (this) {
        notifyAll();
      }
    }
  }
570288
public void run() {
        this.running = true;

        while (this.running) {
            DatagramPacket packet = new DatagramPacket(this.buf, this.buf.length);
            try {
                this.socket.receive(packet);
            } catch (IOException ignored) {
                continue;
            }

            byte[] worker = new byte[2];
            System.arraycopy(this.buf, 2, worker, 0, 2);
            int length = (int)ByteArray.fromBytes(worker);
            worker = new byte[length];
            System.arraycopy(this.buf, 0, worker, 0, length);
            Command msg = new Command(worker, tk);
            InetAddress address = packet.getAddress();
            int port = packet.getPort();
            int timeStamp = (int)(System.currentTimeMillis() / 1000L);
            Response resp;
            if (msg.isHello()){
                resp = new Response(this.tk, this.deviceId, timeStamp);
            } else {
                if (msg.getDeviceID() != this.deviceId) continue;
                Object data = executeCommand(msg.getMethod(),msg.getParams());
                if (data == null){
                    data = "unknown_method";
                }
                resp = new Response(this.tk, this.deviceId, timeStamp, msg.getPayloadID(), data);
            }
            byte[] respMsg = resp.create();
            System.arraycopy(respMsg,0,this.buf,0,respMsg.length);
            packet = new DatagramPacket(buf, respMsg.length, address, port);

            try {
                this.socket.send(packet);
            } catch (IOException ignored) {
            }
        }
        this.socket.close();
    }
514481
def run(self):
    
    # From now on, it's multi-thread. Let the force be with them.
    st = self.stream._stream

    for chunk in chunks(self.audio,
                        size=self.chunk_size*self.nchannels,
                        dfmt=self.dfmt):
      #Below is a faster way to call:
      #  self.stream.write(chunk, self.chunk_size)
      self.write_stream(st, chunk, self.chunk_size, False)
      if not self.go.is_set():
        self.stream.stop_stream()
        if self.halting:
          break
        self.go.wait()
        self.stream.start_stream()

    # Finished playing! Destructor-like step: let's close the thread
    with self.lock:
      if self in self.device_manager._threads: # If not already closed
        self.stream.close()
        self.device_manager.thread_finished(self)
1112158
public void run() {
        try {
            callback.open();
            this.request = getLogRequest(true);
            final HttpResponse response = client.execute(request);
            parseResponse(response);
        } catch (LogCallback.DoneException e) {
            // Signifies we're finished with the log stream.
        } catch (IOException e) {
            callback.error("IO Error while requesting logs: " + e + " " + Thread.currentThread().getName());
        } finally {
            callback.close();
        }
    }
565390
def run(self):
        
        loop = GLib.MainLoop()
        context = loop.get_context()
        while True:
            time.sleep(0.1)
            if context.pending():
                context.iteration()
                self._manager[ATTR_POSITION] = self._position()
            try:
                method, args = self._task_queue.get(False)
                getattr(self, method)(**args)
            except queue.Empty:
                pass
            if self.state != STATE_IDLE:
                continue
            try:
                uri = self._media_queue.get(False)
                self.media(uri)
            except queue.Empty:
                pass
1007631
def run(self):
        """"""
        event_handler = Handler()
        threads = []
        paths = [os.path.join(cwd, "content"), os.path.join(cwd, "templates")]

        for i in paths:
            targetPath = str(i)
            self.observer.schedule(event_handler, targetPath, recursive=True)
            threads.append(self.observer)

        self.observer.start()

        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("\nObserver stopped.")

        self.observer.join()
709375
public void run() {
        if(log.isDebugEnabled()) {
            log.debug("ListenerThread Starting.");
        }

        while(running) {
            try {
                Socket clientSocket = serverSocket.accept();

                WorkerThread worker = new WorkerThread(container, clientSocket);
                worker.start();

            } catch(SocketTimeoutException ste) {
                // Ignore. We receive one of these every second, when the accept()
                // method times out. This is done to give us the opportunity to break
                // out of the blocking accept() call in order to shut down cleanly.

            } catch(Exception e) {
                if(log.isErrorEnabled()) {
                    log.error("Error Accepting: " + e.toString(), e);
                }
            }
        }

		try {
			serverSocket.close();
			
		} catch (IOException e) {
			if(log.isErrorEnabled()) {
				log.error("Error closing the server socket: " + e.toString(), e);
			}
		}
    }
625120
def run_in_executor(self, callback):
        
        # Wait until the main thread is idle.
        # We start the thread by using `call_from_executor`. The event loop
        # favours processing input over `calls_from_executor`, so the thread
        # will not start until there is no more input to process and the main
        # thread becomes idle for an instant. This is good, because Python
        # threading favours CPU over I/O -- an autocompletion thread in the
        # background would cause a significantly slow down of the main thread.
        # It is mostly noticable when pasting large portions of text while
        # having real time autocompletion while typing on.
        def start_executor():
            threading.Thread(target=callback).start()
        self.call_from_executor(start_executor)
1137685
@Override
  public void run()
  {
    try {
      while (! isClosed() && _is.read() > 0 && _in.readMessage(_is)) {
        ServiceRef.flushOutbox();
      }
    } catch (EOFException e) {
      log.finer(this + " end of file");
      
      if (log.isLoggable(Level.ALL)) {
        log.log(Level.ALL, e.toString(), e);
      }
    } catch (SocketException e) {
      e.printStackTrace();
      log.finer(this + " socket closed:" + e);
      
      if (log.isLoggable(Level.ALL)) {
        log.log(Level.ALL, e.toString(), e);
      }
    } catch (IOException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    } catch (Throwable e) {
      e.printStackTrace();
      throw e;
    } finally {
      close();
    }
  }
323013
def run(self):
        """"""
        # pylint: disable=broad-except
        self.protocol = self.protocol_factory()
        try:
            self.protocol.connection_made(self)
        except Exception as exc:
            self.alive = False
            self.protocol.connection_lost(exc)
            self._connection_made.set()
            return
        error = None
        self._connection_made.set()
        while self.alive:
            data = None
            try:
                available_socks = self._check_socket()
                if available_socks[0]:
                    data = self.sock.recv(120)
            except Exception as exc:
                error = exc
                break
            else:
                if data:
                    try:
                        self.protocol.data_received(data)
                    except Exception as exc:
                        error = exc
                        break
            try:
                self._check_connection()
            except OSError as exc:
                error = exc
                break
            time.sleep(0.02)  # short sleep to avoid burning 100% cpu
        self.alive = False
        self.protocol.connection_lost(error)
        self.protocol = None
53655
def run(self):
        """"""
        notice('Starting output thread', self.color)
        o = Thread(target=self.__output_thread, name='output')
        o.start()
        self.threads.append(o)
        try:
            notice('Starting input thread', self.color)
            self.__input_thread()
        except KeyboardInterrupt:
            self.__shutdown()
1117014
def run(self):
        
        listener_thr = _spawn(self.receiver.run)
        callback_thr = _spawn(self.callbacks.run)
        sender_thr = _spawn(self.sender.run)
        logger_thr = _spawn(self.logger.run)

        self.connect()
        try:
            yield
        finally:
            self.stop()

            # Wait for the listener to finish.
            listener_thr.join()
            self.callbacks.put('shutdown')

            # Tell the other threads to finish, and wait for them.
            for obj in [self.callbacks, self.sender, self.logger]:
                obj.stop()
            for thr in [callback_thr, sender_thr, logger_thr]:
                thr.join()
601469
public void run(){
      switch(mode){
        case START_MODE:
         try{
           startSession();
         }catch(IOException ioe){
           handleException(ioe);
           //ioe.printStackTrace();
         }finally{
           abort();
           if(auth!=null) auth.endSession();
           log("Main thread(client->remote)stopped.");
         }
        break;
        case ACCEPT_MODE:
          try{
            doAccept();
            mode = PIPE_MODE;
            pipe_thread1.interrupt(); //Tell other thread that connection have
                                      //been accepted.
            pipe(remote_in,out);
          }catch(IOException ioe){
            //log("Accept exception:"+ioe);
            handleException(ioe);
          }finally{
            abort();
            log("Accept thread(remote->client) stopped");
          }
        break;
        case PIPE_MODE:
         try{
            pipe(remote_in,out);
         }catch(IOException ioe){
         }finally{
            abort();
            log("Support thread(remote->client) stopped");
         }
        break;
        case ABORT_MODE:
        break;
        default:
         log("Unexpected MODE "+mode);
      }
   }
28168
def run_in_thread_pool(self, pool_size=None, func=None, *args):
        """"""
        executor = Pool(pool_size)
        return self.loop.run_in_executor(executor, func, *args)
1157129
def run_locally(self):
        """"""
        self.thread = threading.Thread(target=self.execute_locally)
        self.thread.daemon = True # So that they die when we die
        self.thread.start()