Пример #1
1
  private void startNetwork() throws IOException {
    InetAddress addr = InetAddress.getLocalHost();
    myHostAddress = addr.getHostAddress();
    selfUser = new User(this.userName, this.myHostAddress, this.unicastPort);
    group = InetAddress.getByName(MULTICAST_ADDRESS);
    multicastSocket = new MulticastSocket(MULTICAST_PORT);
    // ? multicastSocket.setLoopbackMode(true);

    // listen for messages sent on this multicast socket:
    multicastListenThread =
        new Thread(
            new Runnable() {
              @Override
              public void run() {
                // this thread is started within the unicast listen thread, so the latter must
                // be running before we sent our multicast connect message
                System.out.println("multicast listen thread running");
                try {
                  multicastSocket.joinGroup(group);
                  String message =
                      "connect::name="
                          + userName
                          + "::host="
                          + myHostAddress
                          + "::port="
                          + unicastPort;
                  DatagramPacket packet =
                      new DatagramPacket(
                          message.getBytes(), message.length(), group, MULTICAST_PORT);
                  multicastSocket.send(packet);
                } catch (IOException e) {
                  e.printStackTrace();
                }
                byte[] inBuffer = new byte[1000];
                DatagramPacket recv = new DatagramPacket(inBuffer, inBuffer.length);
                while (true) {
                  try {
                    multicastSocket.receive(recv);
                    processPacket(recv, true);
                  } catch (IOException e) {
                    if (e instanceof SocketException && e.getMessage().equals("socket closed")) {
                      System.out.println("inner thread terminating as socket now closed");
                      break;
                    }
                    e.printStackTrace();
                    break;
                  }
                }
              }
            });
    // listen for messages sent on unicast socket
    unicastListenThread = new Thread(this);
    unicastListenThread.setPriority(unicastListenThread.getPriority() + 1);
    unicastListenThread.start();
    System.out.println(
        "unicastListenThread started at priority " + unicastListenThread.getPriority());
  }
Пример #2
1
  public static void main(String[] args) {
    System.out.println("main method");

    Thread th = Thread.currentThread();
    System.out.println("Original thread name: " + th.getName());
    System.out.println("Original thread priority: " + th.getPriority());

    th.setName("main-thread");
    th.setPriority(7);

    System.out.println("Changed thread name: " + th.getName());
    System.out.println("Changed thread priority: " + th.getPriority());
  }
  @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();
  }
Пример #4
1
    public Thread newThread(final Runnable r) {
      Thread t = new Thread(r, mTag + "-" + mCount.getAndIncrement());

      if (t.getPriority() != Thread.MIN_PRIORITY) t.setPriority(Thread.MIN_PRIORITY);

      return t;
    }
Пример #5
1
  // This method recursively visits all thread groups under `group'.
  public static void visit(ThreadGroup group, int level) {
    // Get threads in `group'
    int numThreads = group.activeCount();
    Thread[] threads = new Thread[numThreads * 2];
    numThreads = group.enumerate(threads, false);

    System.out.println("Threadgroup: " + group.getName());

    // Enumerate each thread in `group'
    for (int i = 0; i < numThreads; i++) {
      // Get thread
      Thread thread = threads[i];
      System.out.println(
          "Thread: "
              + thread.getName()
              + "("
              + thread.getPriority()
              + ") has state "
              + thread.getState());
    }

    // Get thread subgroups of `group'
    int numGroups = group.activeGroupCount();
    ThreadGroup[] groups = new ThreadGroup[numGroups * 2];
    numGroups = group.enumerate(groups, false);

    // Recursively visit each subgroup
    for (int i = 0; i < numGroups; i++) {
      visit(groups[i], level + 1);
    }
  }
 public Thread newThread(Runnable r) {
   Thread t =
       new GSThread(group, r, namePrefix + threadNumber.get(), threadNumber.getAndIncrement());
   if (t.isDaemon()) t.setDaemon(false);
   if (t.getPriority() != Thread.MAX_PRIORITY) t.setPriority(Thread.MAX_PRIORITY);
   return t;
 }
Пример #7
1
 private SimpleTimer() {
   final Thread thread = Thread.currentThread();
   final int currentPrio = thread.getPriority();
   try {
     // need this becase the timer's thread will inherit the priority on creation
     thread.setPriority(Thread.MIN_PRIORITY + 1);
     ourTimer = new Timer(THREAD_NAME, true);
   } finally {
     thread.setPriority(currentPrio);
   }
 }
 @Override
 @TaskDescription("Background log writing")
 public void run() {
   final Thread currentThread = Thread.currentThread();
   final int originalPriority = currentThread.getPriority();
   currentThread.setPriority(threadPriority);
   try {
     runLogging();
   } finally {
     // reset to previous value
     currentThread.setPriority(originalPriority);
   }
 };
Пример #9
1
 @Override
 public void run() {
   Thread thread = new Thread("Cheating Essentials Main Thread");
   thread.setName("Cheating Essentials Main Thread");
   thread.setPriority(3);
   thread.start();
   CELogAgent.logInfo(Strings.THREAD_NAME + " - Starting in " + Strings.MINECRAFT_VERSION + "...");
   if (debugMode) {
     CELogAgent.logInfo("Thread priority: " + thread.getPriority());
     CELogAgent.logInfo("Thread State (true / false): " + thread.isAlive());
     CELogAgent.logInfo("Thread ID: " + thread.getId());
     CELogAgent.logInfo("Thread Hashcode: " + thread.hashCode());
   }
   CELogAgent.logInfo(Strings.THREAD_NAME + " Started " + thread.toString());
 }
Пример #10
0
 /**
  * Initialize a Thread.
  *
  * @param target the object whose run() method gets called
  * @param name the name of the new thread
  */
 private void init(Runnable target, String name) {
   Thread parent = currentThread();
   this.target = target;
   this.name = name.toCharArray();
   this.priority = parent.getPriority();
   setPriority(priority);
 }
Пример #11
0
  private void showDefaultInfo(ThreadGroup grp) {
    TreeSet<Thread> threadSet =
        new TreeSet<Thread>(
            new Comparator<Thread>() {
              @Override
              public int compare(Thread t1, Thread t2) {
                return Long.valueOf(t1.getId()).compareTo(t2.getId());
              }
            });
    findThreads(grp, threadSet);

    PrintWriter out = getOutput().getPrintWriter();
    for (final Thread thread : threadSet) {
      VmThread vmThread =
          AccessController.doPrivileged(
              new PrivilegedAction<VmThread>() {
                public VmThread run() {
                  return ThreadHelper.getVmThread(thread);
                }
              });
      out.println(
          " "
              + thread.getId()
              + SEPARATOR
              + thread.getName()
              + SEPARATOR
              + thread.getPriority()
              + SEPARATOR
              + vmThread.getThreadStateName());
    }
  }
Пример #12
0
  private static void writeThreadInfo(PrintWriter pw, Thread thread, State state) {

    pw.printf("Main: Id %d - %s\n", thread.getId(), thread.getName());
    pw.printf("Main:Prioity: %d\n", thread.getPriority());
    pw.printf("Main:Old state:%s\n", state);
    pw.printf("Main:New state:%s\n", thread.getState());
    pw.printf("Main:***********************************\n");
  }
Пример #13
0
 public static void main(String[] args) {
   Thread thread = Thread.currentThread();
   System.out.println("Thread: " + thread);
   System.out.println("Thread Id: " + thread.getId());
   System.out.println("Thread Name: " + thread.getName());
   System.out.println("Thread Group: " + thread.getThreadGroup());
   System.out.println("Thread Priority: " + thread.getPriority());
 }
Пример #14
0
 public static String getThreadSignature() {
   Thread t = Thread.currentThread();
   long l = t.getId();
   String name = t.getName();
   long p = t.getPriority();
   String gname = t.getThreadGroup().getName();
   return (name + ":(id)" + l + ":(priority)" + p + ":(group)" + gname);
 }
Пример #15
0
 public void drop(DropTargetDropEvent dtde) {
   dtde.acceptDrop(DnDConstants.ACTION_COPY);
   DataFlavor[] flavors = null;
   try {
     Transferable t = dtde.getTransferable();
     iterator = null;
     flavors = t.getTransferDataFlavors();
     if (IJ.debugMode) IJ.log("DragAndDrop.drop: " + flavors.length + " flavors");
     for (int i = 0; i < flavors.length; i++) {
       if (IJ.debugMode) IJ.log("  flavor[" + i + "]: " + flavors[i].getMimeType());
       if (flavors[i].isFlavorJavaFileListType()) {
         Object data = t.getTransferData(DataFlavor.javaFileListFlavor);
         iterator = ((List) data).iterator();
         break;
       } else if (flavors[i].isFlavorTextType()) {
         Object ob = t.getTransferData(flavors[i]);
         if (!(ob instanceof String)) continue;
         String s = ob.toString().trim();
         if (IJ.isLinux() && s.length() > 1 && (int) s.charAt(1) == 0) s = fixLinuxString(s);
         ArrayList list = new ArrayList();
         if (s.indexOf("href=\"") != -1 || s.indexOf("src=\"") != -1) {
           s = parseHTML(s);
           if (IJ.debugMode) IJ.log("  url: " + s);
           list.add(s);
           this.iterator = list.iterator();
           break;
         }
         BufferedReader br = new BufferedReader(new StringReader(s));
         String tmp;
         while (null != (tmp = br.readLine())) {
           tmp = java.net.URLDecoder.decode(tmp.replaceAll("\\+", "%2b"), "UTF-8");
           if (tmp.startsWith("file://")) tmp = tmp.substring(7);
           if (IJ.debugMode) IJ.log("  content: " + tmp);
           if (tmp.startsWith("http://")) list.add(s);
           else list.add(new File(tmp));
         }
         this.iterator = list.iterator();
         break;
       }
     }
     if (iterator != null) {
       Thread thread = new Thread(this, "DrawAndDrop");
       thread.setPriority(Math.max(thread.getPriority() - 1, Thread.MIN_PRIORITY));
       thread.start();
     }
   } catch (Exception e) {
     dtde.dropComplete(false);
     return;
   }
   dtde.dropComplete(true);
   if (flavors == null || flavors.length == 0) {
     if (IJ.isMacOSX())
       IJ.error(
           "First drag and drop ignored. Please try again. You can avoid this\n"
               + "problem by dragging to the toolbar instead of the status bar.");
     else IJ.error("Drag and drop failed");
   }
 }
Пример #16
0
  public Thread newThread(Runnable r) {

    Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement());
    t.setDaemon(true);
    if (t.getPriority() != Thread.NORM_PRIORITY) {
      t.setPriority(Thread.NORM_PRIORITY);
    }
    return t;
  }
Пример #17
0
 public void update() {
   Thread th = Thread.currentThread();
   for (int i = 11; i <= 20; i++) {
     System.out.println("Update : " + i + "\t" + th.getName() + "\t" + th.getPriority());
     try {
       Thread.sleep(1000);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Пример #18
0
    public Thread newThread(Runnable r) {
      String name = threadName + "-" + threadNum.getAndIncrement();

      Thread t = new Thread(r, name);

      if (t.isDaemon()) t.setDaemon(false);

      if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);

      return t;
    }
Пример #19
0
 @Override
 public Thread newThread(Runnable r) {
   Thread t = new Thread(null, r, "hj", 0);
   if (t.isDaemon()) {
     t.setDaemon(false);
   }
   if (t.getPriority() != Thread.NORM_PRIORITY) {
     t.setPriority(Thread.NORM_PRIORITY);
   }
   return t;
 }
  @Override
  public Thread newThread(Runnable r) {
    Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);

    if (t.isDaemon()) t.setDaemon(false);
    // I can't really see that we want non-daemon threads...
    // Seems we might get problem with daemon-threads?? Does this mess up join after invoke??
    // t.setDaemon(true);
    if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
    return t;
  }
Пример #21
0
 public static void startRDPServer() {
   if (rdpServerStarted) return;
   rdpServerStarted = true;
   rdpServerThread = new Thread(rdpServer, "RDPServer");
   retryThread = new Thread(new RetryThread(), "RDPRetry");
   packetCallbackThread = new Thread(new PacketCallbackThread(), "RDPCallback");
   if (Log.loggingNet) Log.net("static - starting rdpserver thread");
   try {
     selector = Selector.open();
   } catch (Exception e) {
     Log.exception("RDPServer caught exception opening selector", e);
     System.exit(1);
   }
   rdpServerThread.setPriority(rdpServerThread.getPriority() + 2);
   if (Log.loggingDebug)
     Log.debug(
         "RDPServer: starting rdpServerThread with priority " + rdpServerThread.getPriority());
   rdpServerThread.start();
   retryThread.start();
   packetCallbackThread.start();
 }
Пример #22
0
  /**
   * Traverse the ThreadGroups threads and its child ThreadGroups printing information for each
   * thread found. If 'threadName' is non-null, only print information for the thread that matches
   * the name.
   *
   * @param grp the ThreadGroup to traverse
   * @param out the destination for output
   * @param threadName if non-null, only display this thread.
   */
  private void showThreads(ThreadGroup grp, PrintWriter out, String threadName) {
    if (threadName == null) {
      out.println(GROUP + grp.getName());
    }

    final int max = grp.activeCount() * 2;
    final Thread[] ts = new Thread[max];
    grp.enumerate(ts);

    for (int i = 0; i < max; i++) {
      final Thread t = ts[i];
      if (t != null) {
        if ((threadName == null) || threadName.equals(t.getName())) {
          VmThread vmThread =
              AccessController.doPrivileged(
                  new PrivilegedAction<VmThread>() {
                    public VmThread run() {
                      return ThreadHelper.getVmThread(t);
                    }
                  });
          out.println(
              SLASH_T
                  + t.getId()
                  + SEPARATOR
                  + t.getName()
                  + SEPARATOR
                  + t.getPriority()
                  + SEPARATOR
                  + vmThread.getThreadStateName());
          if (threadName != null) {
            final Object[] trace = VmThread.getStackTrace(vmThread);
            final int traceLen = trace.length;
            out.println(SLASH_T + SLASH_T + TRACE);
            for (int k = 0; k < traceLen; k++) {
              out.println(SLASH_T + SLASH_T + trace[k]);
            }
            return;
          }
        }
      }
    }

    final int gmax = grp.activeGroupCount() * 2;
    final ThreadGroup[] tgs = new ThreadGroup[gmax];
    grp.enumerate(tgs);
    for (int i = 0; i < gmax; i++) {
      final ThreadGroup tg = tgs[i];
      if (tg != null) {
        showThreads(tg, out, threadName);
      }
    }
  }
Пример #23
0
  @Override
  public void query(QueryContext context, String queryString, MetadataCallback callback) {
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();

    ArrayList<ThreadCpuUsage> usages = new ArrayList<ThreadCpuUsage>();

    for (long tid : bean.getAllThreadIds()) {
      long time = bean.getThreadCpuTime(tid);
      usages.add(new ThreadCpuUsage(tid, time));
    }

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
    }

    Map<Thread, StackTraceElement[]> stacks = Thread.getAllStackTraces();

    for (long tid : bean.getAllThreadIds()) {
      ThreadCpuUsage usage = find(usages, tid);
      if (usage != null) usage.secondTime = bean.getThreadCpuTime(tid);
    }

    Collections.sort(usages);

    for (ThreadCpuUsage usage : usages) {
      long elapsed = usage.secondTime - usage.firstTime;
      // remove just created thread or sleeping threads (noisy)
      if (elapsed <= 0) continue;

      StringBuilder sb = new StringBuilder();
      Thread t = findThread(stacks, usage.tid);
      if (t == null) continue;

      StackTraceElement[] stack = findStack(stacks, usage.tid);
      for (StackTraceElement el : stack) {
        sb.append(
            String.format(
                "%s.%s %s\n", el.getClassName(), el.getMethodName(), getFileAndLineNumber(el)));
      }

      Map<String, Object> m = new HashMap<String, Object>();
      m.put("tid", t.getId());
      m.put("name", t.getName());
      m.put("state", t.getState().toString());
      m.put("priority", t.getPriority());
      m.put("usage", elapsed);
      m.put("stacktrace", sb.toString());

      callback.onPush(new Row(m));
    }
  }
Пример #24
0
    public Thread newThread(Runnable r) {
      if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("creating new thread");
      }

      Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
      t.setDaemon(isDaemon);

      if (t.getPriority() != Thread.NORM_PRIORITY) {
        t.setPriority(Thread.NORM_PRIORITY);
      }
      return t;
    }
Пример #25
0
  public static void main(String[] args) {
    Thread ct = Thread.currentThread();
    System.out.println(ct.getName());
    System.out.println(ct.getStackTrace());
    System.out.println(ct.getPriority());

    try {
      ct.sleep(2000);
      System.out.println(ct.getState());
    } catch (InterruptedException e) {
      System.out.println("поток поломался");
    }
  }
  /**
   * Logs the exception with information about which thread the exception happened in, and notifies
   * listeners.
   *
   * @param thread The thread that got the exception.
   * @param throwable The exception the thread got.
   */
  @Override
  public void uncaughtException(final Thread thread, final Throwable throwable) {
    LOG.log(
        Level.SEVERE,
        "UncaughtException in thread: "
            + thread.getName()
            + " (id "
            + thread.getId()
            + ", priority "
            + thread.getPriority()
            + ")",
        throwable);

    for (final UncaughtExceptionListener listener : listeners) {
      listener.uncaughtException(thread, throwable);
    }
  }
Пример #27
0
 /** 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);
     }
   }
 }
Пример #28
0
  protected void printFullThreadDump() {
    StringBundler sb = new StringBundler();

    sb.append("Full thread dump ");
    sb.append(System.getProperty("java.vm.name"));
    sb.append(" ");
    sb.append(System.getProperty("java.vm.version"));
    sb.append("\n\n");

    Map<Thread, StackTraceElement[]> stackTraces = Thread.getAllStackTraces();

    for (Map.Entry<Thread, StackTraceElement[]> entry : stackTraces.entrySet()) {

      Thread thread = entry.getKey();
      StackTraceElement[] elements = entry.getValue();

      sb.append("\"");
      sb.append(thread.getName());
      sb.append("\"");

      if (thread.getThreadGroup() != null) {
        sb.append(" (");
        sb.append(thread.getThreadGroup().getName());
        sb.append(")");
      }

      sb.append(", priority=");
      sb.append(thread.getPriority());
      sb.append(", id=");
      sb.append(thread.getId());
      sb.append(", state=");
      sb.append(thread.getState());
      sb.append("\n");

      for (int i = 0; i < elements.length; i++) {
        sb.append("\t");
        sb.append(elements[i]);
        sb.append("\n");
      }

      sb.append("\n");
    }

    System.out.println(sb);
  }
Пример #29
0
  protected void startGameCanvasRunnableInterface() throws Exception {
    // LogUtil.put(LogFactory.getInstance(CommonStrings.getInstance().START, this,
    // "startGameCanvasRunnableInterface"));
    thread =
        thread =
            ThreadFactoryUtil.getInstance().getInstance(this.allbinaryGameCanvasRunnableInterface);

    LogUtil.put(
        LogFactory.getInstance(
            "Thread Priority: " + thread.getPriority(), this, "startGameCanvasRunnableInterface"));

    // canvasThread.setPriority(Thread.NORM_PRIORITY + 2);
    // thread.setPriority(Thread.MAX_PRIORITY);

    this.allbinaryGameCanvasRunnableInterface.setThread(thread);

    thread.start();
  }
Пример #30
0
 @Override
 public void run() {
   System.out.println("unicast listen thread running");
   byte[] data = new byte[100];
   DatagramPacket packet = new DatagramPacket(data, data.length);
   try {
     multicastListenThread.start();
     System.out.println(
         "multicastListenThread started at priority " + multicastListenThread.getPriority());
     unicastSocket = new DatagramSocket(unicastPort);
     while (true) {
       unicastSocket.receive(packet);
       processPacket(packet, false);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }