/** Create a wrapper over a new StringFilter. */
  public StringFilterWrapper() {
    Thread thread;

    mFilter = new StringFilter();
    mFilter.setCaseSensitive(true);

    // add the text pattern
    mPattern = new JTextArea(2, 20);
    mPattern.setBorder(new BevelBorder(BevelBorder.LOWERED));
    add(mPattern);
    mPattern.getDocument().addDocumentListener(this);
    mPattern.setText(mFilter.getPattern());

    // add the case sensitivity flag
    mCaseSensitivity = new JCheckBox("Case Sensitive");
    add(mCaseSensitivity);
    mCaseSensitivity.addActionListener(this);
    mCaseSensitivity.setSelected(mFilter.getCaseSensitive());

    // add the locales choice
    mLocale = new JComboBox();
    synchronized (mLocale) {
      mLocale.addItem(mFilter.getLocale().getDisplayName());
      thread = new Thread(this);
      thread.setName("locale_getter");
      thread.setPriority(Thread.MIN_PRIORITY);
      thread.run();
    }
    add(mLocale);
    mLocale.addActionListener(this);
    mLocale.setSelectedIndex(0);
    mLocale.setVisible(!mFilter.getCaseSensitive());
  }
示例#2
0
  @Override
  public boolean onTouchEvent(android.view.MotionEvent ev) {
    if ((ev.getAction() == MotionEvent.ACTION_DOWN)
        || (ev.getAction() == MotionEvent.ACTION_MOVE)) {
      long time = System.currentTimeMillis();
      if (time >= lastRefreshTime + Constants.MAP_REFRESH_PERIOD) {
        lastRefreshTime = time;
        Thread refreshThread =
            new Thread(
                new Runnable() {

                  @Override
                  public void run() {
                    refresh();
                  }
                });
        refreshThread.run();
      }
    }
    if ((ev.getAction() == MotionEvent.ACTION_UP)
        || (ev.getAction() == MotionEvent.ACTION_CANCEL)
        || (ev.getAction() == MotionEvent.ACTION_OUTSIDE)) {
      Thread refreshThread =
          new Thread(
              new Runnable() {

                @Override
                public void run() {
                  refresh();
                }
              });
      refreshThread.run();
    }
    return super.onTouchEvent(ev);
  }
示例#3
0
文件: Ex1_3.java 项目: trahasch/SPPP
 public static void main(String[] args) {
   final Thread t1 =
       new Thread(
           new Runnable() {
             public void run() {
               while (true) {
                 synchronized (this) {
                   Printer.print();
                 }
               }
             }
           });
   final Thread t2 =
       new Thread(
           new Runnable() {
             public void run() {
               while (true) {
                 synchronized (this) {
                   Printer.print();
                 }
               }
             }
           });
   t1.run();
   t2.run();
 }
 public void start() {
   final double[] time = new double[accuracy];
   Thread t =
       new Thread() {
         public void run() {
           long currentTime = 0;
           for (int i = 0; i < accuracy; i++) {
             try {
               currentTime = System.nanoTime();
               if (toBenchmark != null) toBenchmark.benchMark();
               else if (runnable != null) runnable.run();
               else throw new NullPointerException();
               time[i] = System.nanoTime() - currentTime;
             } catch (NullPointerException e) {
               System.out.println("ERROR : ");
               e.printStackTrace();
             }
           }
         }
       };
   // Run it once to for class loading-times, etc.
   int tmp = accuracy;
   accuracy = 1;
   t.run();
   accuracy = tmp;
   t.run();
   double sum = 0;
   // Find the mean and print the result
   for (double d : time) sum += d;
   printResult(sum / time.length);
 }
  public void testThreadLocalCommandContext() throws Exception {
    ThreadLocalExtendedCommandContext threadLocalCommandContext =
        new ThreadLocalExtendedCommandContext();
    TestRunnable testRunnable1 = new TestRunnable(threadLocalCommandContext, 1);
    Thread thread1 = this.buildThread(testRunnable1);
    thread1.run();

    TestRunnable testRunnable2 = new TestRunnable(threadLocalCommandContext, 2);
    Thread thread2 = this.buildThread(testRunnable2);
    thread2.run();

    TestRunnable testRunnable3 = new TestRunnable(threadLocalCommandContext, 3, null);
    Thread thread3 = this.buildThread(testRunnable3);
    thread3.run();

    thread1.join();
    thread2.join();
    thread3.join();

    assertEquals(1, testRunnable1.testCommand.count);
    assertEquals(1, testRunnable1.testCommandContext.count);

    assertEquals(2, testRunnable2.testCommand.count);
    assertEquals(2, testRunnable2.testCommandContext.count);

    assertEquals(3, testRunnable3.testCommand.count);
    assertNull(testRunnable3.testCommandContext);
  }
  public void testCompetingThreadsOnMultipleDbInstances() throws Exception {
    // the idea behind this test is to simulate a rexster environment where two graphs of the same
    // type
    // are being mutated by multiple threads.  the test itself surfaced issues with OrientDB in such
    // an environment and remains relevant for any graph that might be exposed through rexster.

    final TransactionalGraph graph1 = (TransactionalGraph) graphTest.generateGraph("first");
    final TransactionalGraph graph2 = (TransactionalGraph) graphTest.generateGraph("second");

    if (!graph1.getFeatures().isRDFModel) {

      final Thread threadModFirstGraph =
          new Thread() {
            public void run() {
              final Vertex v = graph1.addVertex(null);
              v.setProperty("name", "stephen");
              graph1.stopTransaction(Conclusion.SUCCESS);
            }
          };

      threadModFirstGraph.run();
      threadModFirstGraph.join();

      final Thread threadReadBothGraphs =
          new Thread() {
            public void run() {
              int counter = 0;
              for (Vertex v : graph1.getVertices()) {
                counter++;
              }

              Assert.assertEquals(1, counter);

              counter = 0;
              for (Vertex v : graph2.getVertices()) {
                counter++;
              }

              Assert.assertEquals(0, counter);
            }
          };

      threadReadBothGraphs.run();
      threadReadBothGraphs.join();
    }

    graph1.shutdown();
    graph2.shutdown();
  }
    @Override
    public void run() {
      super.run();

      try {
        do {
          if (myAnim.start == -1 || myAnim.end == -1) {
            // this is a single image, not an animation
            tryLoadBitmap(myAnim.filename);
          } else {
            for (int i = myAnim.start; i <= myAnim.end; i++) {
              boolean bitmapLoaded;
              bitmapLoaded =
                  tryLoadBitmap(myAnim.filename + new DecimalFormat("0000").format(i) + ".png");
              if (!bitmapLoaded) {
                break;
              }
            }
          }
        } while (myAnim.loop);
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        if (shouldTurn) {
          myCanvasView.setmLookingRight(!myCanvasView.ismLookingRight());
        }
      }
    }
示例#8
0
  // test for http://jira.codehaus.org/browse/PERFFORJ-22
  public void testFlushOnShutdown() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j-shutdownbug.xml"));

    // make a bunch of logs, but not enough to go over the timeslice.
    for (int i = 0; i < 5; i++) {
      StopWatch stopWatch = new Log4JStopWatch("tag1");
      Thread.sleep(10 * i);
      stopWatch.stop();
    }

    // at this point none of the file appenders will have written anything because they haven't been
    // flushed
    assertEquals("", FileUtils.readFileToString(new File("target/stats-shutdownbug.log")));
    assertEquals("", FileUtils.readFileToString(new File("target/graphs-shutdownbug.log")));

    // now, to simulate shutdown, get the async appender and run the shutdown hook. We need to use
    // reflection
    // because the shutdown hook is private.
    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");
    Field shutdownField = appender.getClass().getDeclaredField("shutdownHook");
    shutdownField.setAccessible(true);
    Thread shutdownHook = (Thread) shutdownField.get(appender);
    shutdownHook.run();

    // now there should be data in the files
    assertFalse("".equals(FileUtils.readFileToString(new File("target/stats-shutdownbug.log"))));
    assertFalse("".equals(FileUtils.readFileToString(new File("target/graphs-shutdownbug.log"))));
  }
 public synchronized void start() {
   thread = new Thread(this);
   running = true;
   // thread.start();
   System.out.println("Thread started from within");
   thread.run();
 }
示例#10
0
    @Override
    public void run() {
      super.run();
      while (true) {
        if (service != null) {
          try {
            long value = service.confGetRxTxLevel(0);
            runOnUiThread(
                new UpdateConfLevelRunnable((int) ((value >> 8) & 0xff), (int) (value & 0xff)));
          } catch (RemoteException e) {
            Log.e(THIS_FILE, "Problem with remote service", e);
            break;
          }
        }

        // End of loop, sleep for a while and exit if necessary
        try {
          sleep(100);
        } catch (InterruptedException e) {
          Log.e(THIS_FILE, "Interupted monitor thread", e);
        }
        synchronized (this) {
          if (finished) {
            break;
          }
        }
      }
    }
示例#11
0
 private void loadNoteContentsFromFile(final Note note) {
   Runnable task =
       new Runnable() {
         @Override
         public void run() {
           String contents = "";
           final Encryptor encryptor = new Encryptor(password);
           try {
             FileInputStream inputStream =
                 new FileInputStream(new File(filesDir, note.getFileName()));
             BufferedReader reader =
                 new BufferedReader(new InputStreamReader(new DataInputStream(inputStream)));
             String line;
             while ((line = reader.readLine()) != null) {
               contents = contents + line;
             }
             inputStream.close();
             displayContents(contents);
           } catch (Exception e) {
             e.printStackTrace();
             displayContents("");
           }
         }
       };
   Thread thread = new Thread(task);
   thread.run();
 }
示例#12
0
  @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());
    }
  }
    @Override
    public void run() {
      // TODO Auto-generated method stub
      super.run();
      while (true && !isInterrupted()) {
        if (!view.isShown() && flag == true) {

          view.post(
              new Runnable() {

                @Override
                public void run() {
                  // TODO Auto-generated method stub
                  view.setVisibility(View.VISIBLE);
                  view.layout(0, 0, 1, 1);
                  // CommonUtil.tolog("post");
                  flag = true;
                }
              });
        } else {
          flag = true;
        }

        try {
          Thread.sleep(100);
          // CommonUtil.tolog("Thread sleep");
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
示例#14
0
 @Override
 public final void run() {
   if (!setNativePriority(currentPriority))
     System.err.println("setNativePriority(" + currentPriority + ") has failed!");
   super.run();
   realRun();
 }
示例#15
0
  /* (non-Javadoc)
   * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    final ServletContext ctxt = getServletContext();

    ParamsBean params = new ParamsBean(req, getHostsList());
    if (!allowed(params, getPropertiesManager().adminACL, req, res)) return;

    Thread configthread =
        new Thread("jrds-new-config") {
          @Override
          public void run() {
            Configuration oldConfig = getConfig();
            Configuration newConfig = new Configuration(ctxt);
            oldConfig.stop();
            newConfig.start();
            setConfig(newConfig);
            // Avoid a memory leak in perm gen
            java.beans.Introspector.flushCaches();
            logger.info("Configuration rescaned");
          }
        };
    if (params.getValue("sync") != null) {
      configthread.run();
      return;
    }

    configthread.start();
    res.sendRedirect(req.getContextPath() + "/");
  }
    @Override
    public void run() {
      super.run();

      //				float h2 = (float)myCanvasView.getHeight()/2.0f;
      //				float w2 = (float)myCanvasView.getWidth()/2.0f;
      //				float h2 = clip.height()/2.0f;
      //				float w2 = clip.width()/2.0f;

      float rotstep = (deg - rotation) / 20.0f;
      float scalestep = (scl - scale) / 20.0f;
      for (int i = 0; i < 20; i++) {
        matrixLock.lock();
        matrix.reset();

        // linear interpolation
        //					rotation += rotstep;
        //					matrix.setRotate(rotation,w2,h2);

        scale += scalestep;
        matrix.postScale(scale, scale);

        matrixLock.unlock();

        myCanvasView.postInvalidate();

        try {
          sleep(30);
        } catch (InterruptedException e) {
          Log.i(TAG, "interrupted", e);
          break;
        }
      }
    }
示例#17
0
    @Override
    public void run() {
      super.run();
      try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update("hackme".getBytes());

        byte[] passwordBytes = digest.digest();

        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < passwordBytes.length; i++) {
          hexString.append(Integer.toHexString(0xFF & passwordBytes[i]));
        }

        // Send password to splitter, disabled for tests

        /*socket.getOutputStream().write(hexString.toString().getBytes("UTF-8"));

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        char[] result = new char[32];
        bufferedReader.read(result);
        if (result != null) {
            Log.d("Splitter", "Connection accepted");
        }*/

        running = true;

        new StreamingThread().start();

      } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
      }
    }
示例#18
0
  private void sendFile(PrintWriter output, BufferedReader in)
      throws IOException, NumberFormatException {

    FileSender fileSender = (FileSender) payload;

    output.println(LanguageProtocol.INIT_FILE_TRANS);

    String response = in.readLine();
    if (null != response && response.equals(LanguageProtocol.ACK)) {
      output.println(fileSender.jsonPayload);
      response = in.readLine();

      if (null != response && response.equals(LanguageProtocol.ACCEPT_FILE_TRANS)) {
        output.println(LanguageProtocol.ACK);

        fileSender.port = this.port;
        fileSender.ipAddr = this.serverName;

        fileSender.port = Integer.parseInt(in.readLine());

        Thread thread = new Thread(fileSender);
        thread.run();
      }
    }
  }
    public void run() {
      super.run();
      ar.startRecording();
      // 用于读取的 buffer
      byte[] buffer = new byte[bs];
      isRun = true;
      while (isRun) {
        int r = ar.read(buffer, 0, bs);
        int v = 0;
        // 将 buffer 内容取出,进行平方和运算
        for (int i = 0; i < buffer.length; i++) {
          // 这里没有做运算的优化,为了更加清晰的展示代码
          v += buffer[i] * buffer[i];
          // v += (buffer[i] << 1);
        }
        // 平方和除以数据总长度,得到音量大小。可以获取白噪声值,然后对实际采样进行标准化。
        // 如果想利用这个数值进行操作,建议用 sendMessage 将其抛出,在 Handler 里进行处理。
        // Log.d("spl", String.valueOf(v / (float) r));
        value = v / (float) r;
        // value = (int) (Math.abs((int)(v /(float)r)/10000) >> 1);
        dB = 10 * Math.log10(v / (double) r);

        // MainActivity.SetText(value,dB);
        Log.d("Data:", String.valueOf(value) + "    " + String.valueOf(dB));
        handler.post(
            new Runnable() {
              @Override
              public void run() {
                SetText(value, dB);
              }
            });
      }
      ar.stop();
    }
示例#20
0
  @Override
  public void run() {
    super.run();
    HttpURLConnection con;
    try {
      con = (HttpURLConnection) url.openConnection();
      // con.setRequestMethod("POST");
      // con.setRequestProperty("Range", "betys" + startPosition + "-");
      con.setRequestProperty("User-Agent", "Internet Explorer");
      String sProperty = "bytes=" + startPosition + "-";
      // 告诉服务器book.rar这个文件从nStartPos字节开始传
      con.setRequestProperty("Range", sProperty);

      con.setReadTimeout(6000);
      InputStream inputStream = con.getInputStream();
      byte[] buffer = new byte[1024];
      int len = -1;
      int readFileSize = 0;
      System.out.println(this.getName() + ":" + this.block);
      while (readFileSize <= block && (len = inputStream.read(buffer)) != -1) {
        threadFile.write(buffer, 0, len);
        readFileSize += len; // 累计下载文件大小
      }
      threadFile.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#21
0
 /** 构建一个用户接受server信息的线程 */
 @Override
 public void run() {
   super.run();
   while (true) {
     receiveServerMsg();
   }
 }
示例#22
0
 @Override
 public void run() {
   // TODO Auto-generated method stub
   super.run();
   if (url.equals(ForceTvUtils.paramurl)) {
     LogUtils.write(TAG, "no switch_chan");
     Message msg = handler.obtainMessage();
     msg.obj = playurl;
     msg.what = ForceTvsuc;
     handler.sendMessage(msg);
   } else {
     String xml = HttpClientHelper.DoGet(url);
     if (isrun) {
       LogUtils.write(TAG, "" + xml);
       boolean flag = DomUtils.ParseForceTvXml(xml);
       Message msg = handler.obtainMessage();
       if (flag) {
         msg.obj = playurl;
         msg.what = ForceTvsuc;
         ForceTvUtils.paramurl = url;
       } else {
         msg.what = ForceTvfail;
       }
       handler.sendMessage(msg);
     }
   }
 }
 @Override
 public void run() {
   while (humiditykey) {
     humidity = humiditypreferences.getString("humidity", "----");
     runOnUiThread(
         new Runnable() {
           public void run() {
             if (humidity.equals("----")) {
               if (!outtoastflag) {
                 Toast.makeText(HumidityActivity.this, "湿度传感器未连接", Toast.LENGTH_SHORT).show();
                 humiditytext.setText(humidity);
                 outtoastflag = true;
               }
             } else {
               humiditytext.setText(humidity + "%rh");
               outtoastflag = false;
             }
           }
         });
     try {
       Thread.sleep(1000);
     } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
   super.run();
 }
 @Override
 public void run() {
   final long startTime = System.currentTimeMillis();
   super.run();
   final long endTime = System.currentTimeMillis();
   threadIsDone(this, endTime - startTime);
 }
示例#25
0
    @Override
    public void run() {
      super.run();

      try {
        start = 0;
        end = 0;
        url = null;

        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        String hdr = readHeader(is);
        parseHeader(hdr);
        if (url != null) {
          if (end > start) {
            respond_partial(os);
          } else {
            respond_full(os);
          }
        } else {
          Log.v(TAG, "skip response");
        }
        is.close();
        os.close();
        socket.close();
      } catch (IOException ioe) {
        Log.v(TAG, "io exception");
      }
    }
示例#26
0
 /**
  * Because the checking of very large files for their charset may take some time, we do this
  * concurrently in this method This method does not return anything but it logs an info line if
  * the charset is a good choice and it logs a warning line if the choice was bad.
  *
  * @param file the file to be checked
  * @param givenCharset the charset that we consider to be valid
  * @param concurrent if this shall run concurrently
  */
 public static void checkCharset(
     final File file, final String givenCharset, final boolean concurrent) {
   Thread t =
       new Thread() {
         @Override
         public void run() {
           try {
             Set<String> charsets = FileUtils.detectCharset(file);
             if (charsets.contains(givenCharset)) {
               ConcurrentLog.info(
                   "checkCharset",
                   "appropriate charset '"
                       + givenCharset
                       + "' for import of "
                       + file
                       + ", is part one detected "
                       + charsets);
             } else {
               ConcurrentLog.warn(
                   "checkCharset",
                   "possibly wrong charset '"
                       + givenCharset
                       + "' for import of "
                       + file
                       + ", use one of "
                       + charsets);
             }
           } catch (IOException e) {
           }
         }
       };
   if (concurrent) t.start();
   else t.run();
 }
示例#27
0
  @Override
  public void run() {
    super.run(); // To change body of generated methods, choose Tools | Templates.

    this.f = new File(String.valueOf(this.m_listening_port) + ".txt");
    try {
      this.pw = new PrintWriter(new BufferedWriter(new FileWriter(f)));
    } catch (IOException exception) {
      System.out.println("Erreur lors de la lecture : " + exception.getMessage());
      System.exit(-1);
    }

    while (true) {
      synchronized (this.m_delivered_messages) {
        if (!this.m_delivered_messages.isEmpty()) {
          byte[] data = m_delivered_messages.removeFirst();
          Message message = new Message(null, data);

          this.pw.print(message);

          this.pw.println();
        } else if (has_to_finish) {
          has_finished = true;
          break;
        }
      }
    }
  }
 /** Not relevant to subclasses. */
 @Override
 public final void run() {
   super.run();
   while (true) {
     try {
       synchronized (this) {
         if (abort_) {
           break;
         }
         ioio_ = IOIOFactory.create();
       }
       ioio_.waitForConnect();
       setup();
       while (true) {
         loop();
       }
     } catch (ConnectionLostException e) {
       if (abort_) {
         break;
       }
     } catch (Exception e) {
       Log.e("AbstractIOIOActivity", "Unexpected exception caught", e);
       ioio_.disconnect();
       break;
     } finally {
       try {
         ioio_.waitForDisconnect();
       } catch (InterruptedException e) {
       }
     }
   }
 }
示例#29
0
    @Override
    public void run() {
      super.run();

      byte[] buffer = new byte[4096];

      while (true) {
        int size;
        try {
          if (mFileInputStream == null) {
            return;
          }
          int canRead = mFileInputStream.available();
          if (canRead > 0) {
            buffer = new byte[4096];
            size = mFileInputStream.read(buffer);
            if (size > 0) {
              onDataReceived(buffer, size);
              Log.i(TAG, "ReadThread:" + byteToString(buffer, size));
              size = 0;
            }
          }
          Thread.sleep(1);
        } catch (IOException e) {
          Log.e(TAG, e.getMessage());
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
示例#30
0
  public static void importRDFXMLFile(Repository rdf, String ns, File... files) throws Exception {
    Stack<Thread> threads = new Stack<Thread>();

    Logger log = LoggerFactory.getLogger("RDF/XML Importer");

    for (File file : files) {
      try {
        // multi-threaded load to enjoy multi-core CPUs
        Thread thread = new FileLoadingThread(rdf, file, ns);
        log.info(
            "Loading  file "
                + file
                + " of "
                + new DecimalFormat("###,###,###.###").format(file.length())
                + " bytes"); // , thread " +
        // threads.size());
        System.setProperty("entityExpansionLimit", "1000000");
        thread.run();
      } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Failed to load file " + file.getCanonicalPath(), e);
      }
    }

    while (!threads.isEmpty()) {
      if (!threads.peek().isAlive()) {
        threads.pop();
      }
      Thread.sleep(100);
    }
  }