Java/Threads/Thread Attributes
Содержание
- 1 Get Thread name
- 2 Set Thread Priority
- 3 Thread general interrupt
- 4 ThreadGroup Enumerate
- 5 Thread ID
- 6 Thread interrupt check
- 7 Thread interrupt reset
- 8 Thread Interrupt when calculating Pi
- 9 Thread name
- 10 Thread pending and interrupt
- 11 Thread Priority
- 12 Thread priority information
- 13 Utilities to manage thread ids
Get Thread name
<source lang="java">
public class TwoThreadGetName extends Thread {
public void run() { for (int i = 0; i < 10; i++) { printMsg(); } } public void printMsg() { Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name=" + name); } public static void main(String[] args) { TwoThreadGetName tt = new TwoThreadGetName(); tt.start(); for (int i = 0; i < 10; i++) { tt.printMsg(); } }
}
</source>
Set Thread Priority
<source lang="java">
public class SetPriority extends Object {
private static Runnable makeRunnable() { Runnable r = new Runnable() { public void run() { for (int i = 0; i < 5; i++) { Thread t = Thread.currentThread(); System.out.println("in run() - priority=" + t.getPriority() + ", name=" + t.getName()); try { Thread.sleep(2000); } catch (InterruptedException x) { } } } }; return r; } public static void main(String[] args) { Thread threadA = new Thread(makeRunnable(), "threadA"); threadA.setPriority(8); threadA.start(); Thread threadB = new Thread(makeRunnable(), "threadB"); threadB.setPriority(2); threadB.start(); Runnable r = new Runnable() { public void run() { Thread threadC = new Thread(makeRunnable(), "threadC"); threadC.start(); } }; Thread threadD = new Thread(r, "threadD"); threadD.setPriority(7); threadD.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } threadA.setPriority(3); System.out.println("in main() - threadA.getPriority()=" + threadA.getPriority()); }
}
</source>
Thread general interrupt
<source lang="java">
public class GeneralInterrupt extends Object implements Runnable {
public void run() { try { System.out.println("in run() - about to work2()"); work2(); System.out.println("in run() - back from work2()"); } catch (InterruptedException x) { System.out.println("in run() - interrupted in work2()"); return; } System.out.println("in run() - doing stuff after nap"); System.out.println("in run() - leaving normally"); } public void work2() throws InterruptedException { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted()); Thread.sleep(2000); System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted()); } } } public void work() throws InterruptedException { while (true) { for (int i = 0; i < 100000; i++) { int j = i * 2; } System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted()); if (Thread.interrupted()) { System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted()); throw new InterruptedException(); } } } public static void main(String[] args) { GeneralInterrupt si = new GeneralInterrupt(); Thread t = new Thread(si); t.start(); try { Thread.sleep(2000); } catch (InterruptedException x) { } System.out.println("in main() - interrupting other thread"); t.interrupt(); System.out.println("in main() - leaving"); }
}
</source>
ThreadGroup Enumerate
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
public class EnumerateMain {
public static void main(String[] args) { new EnumerateTest().listCurrentThreads(); }
} class EnumerateTest {
public void listCurrentThreads() { ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); int numThreads = currentGroup.activeCount(); Thread[] listOfThreads = new Thread[numThreads]; currentGroup.enumerate(listOfThreads); for (int i = 0; i < numThreads; i++) System.out.println("Thread #" + i + " = " + listOfThreads[i].getName()); }
}
</source>
Thread ID
<source lang="java">
public class ThreadIDMain extends Object implements Runnable {
private ThreadID var; public ThreadIDMain(ThreadID var) { this.var = var; } public void run() { try { print("var.getThreadID()=" + var.getThreadID()); Thread.sleep(2000); print("var.getThreadID()=" + var.getThreadID()); } catch (InterruptedException x) { } } private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ": " + msg); } public static void main(String[] args) { ThreadID tid = new ThreadID(); ThreadIDMain shared = new ThreadIDMain(tid); try { Thread threadA = new Thread(shared, "threadA"); threadA.start(); Thread.sleep(500); Thread threadB = new Thread(shared, "threadB"); threadB.start(); Thread.sleep(500); Thread threadC = new Thread(shared, "threadC"); threadC.start(); } catch (InterruptedException x) { } }
} class ThreadID extends ThreadLocal {
private int nextID; public ThreadID() { nextID = 10001; } private synchronized Integer getNewID() { Integer id = new Integer(nextID); nextID++; return id; } // override ThreadLocal"s version protected Object initialValue() { print("in initialValue()"); return getNewID(); } public int getThreadID() { Integer id = (Integer) get(); return id.intValue(); } private static void print(String msg) { String name = Thread.currentThread().getName(); System.out.println(name + ": " + msg); }
}
</source>
Thread interrupt check
<source lang="java">
public class InterruptCheck extends Object {
public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println("A: t.isInterrupted()=" + t.isInterrupted()); t.interrupt(); System.out.println("B: t.isInterrupted()=" + t.isInterrupted()); System.out.println("C: t.isInterrupted()=" + t.isInterrupted()); try { Thread.sleep(2000); System.out.println("NOT interrupted"); } catch (InterruptedException x) { System.out.println("Interrupted"); } System.out.println("D: t.isInterrupted()=" + t.isInterrupted()); }
}
</source>
Thread interrupt reset
<source lang="java">
public class InterruptReset extends Object {
public static void main(String[] args) { System.out.println("Thread.interrupted()=" + Thread.interrupted()); Thread.currentThread().interrupt(); System.out.println("Thread.interrupted()=" + Thread.interrupted()); System.out.println("Thread.interrupted()=" + Thread.interrupted()); }
}
</source>
Thread Interrupt when calculating Pi
<source lang="java">
public class PiInterrupt extends Object implements Runnable {
private double latestPiEstimate; public void run() { try { System.out.println("for comparison, Math.PI=" + Math.PI); calcPi(0.000000001); System.out .println("within accuracy, latest pi=" + latestPiEstimate); } catch (InterruptedException x) { System.out.println("INTERRUPTED!! latest pi=" + latestPiEstimate); } } private void calcPi(double accuracy) throws InterruptedException { latestPiEstimate = 0.0; long iteration = 0; int sign = -1; while (Math.abs(latestPiEstimate - Math.PI) > accuracy) { if (Thread.interrupted()) { throw new InterruptedException(); } iteration++; sign = -sign; latestPiEstimate += sign * 4.0 / ((2 * iteration) - 1); } } public static void main(String[] args) { PiInterrupt pi = new PiInterrupt(); Thread t = new Thread(pi); t.start(); try { Thread.sleep(10000); t.interrupt(); } catch (InterruptedException x) { } }
}
</source>
Thread name
<source lang="java">
public class TwoThreadSetName extends Thread {
public void run() { for (int i = 0; i < 10; i++) { printMsg(); } } public void printMsg() { Thread t = Thread.currentThread(); String name = t.getName(); System.out.println("name=" + name); } public static void main(String[] args) { TwoThreadSetName tt = new TwoThreadSetName(); tt.setName("thread"); tt.start(); for ( int i = 0; i < 10; i++ ) { tt.printMsg(); } }
}
</source>
Thread pending and interrupt
<source lang="java">
public class PendingInterrupt extends Object {
public static void main(String[] args) { Thread.currentThread().interrupt(); long startTime = System.currentTimeMillis(); try { Thread.sleep(2000); System.out.println("NOT interrupted"); } catch (InterruptedException x) { System.out.println("Interrupted"); } System.out.println("elapsedTime=" + (System.currentTimeMillis() - startTime)); }
}
</source>
Thread Priority
<source lang="java">
public class PriorityCompete extends Object {
private volatile int count; private boolean yield; private Thread internalThread; private volatile boolean noStopRequested; public PriorityCompete(String name, int priority, boolean yield) { count = 0; this.yield = yield; noStopRequested = true; Runnable r = new Runnable() { public void run() { try { runWork(); } catch (Exception x) { x.printStackTrace(); } } }; internalThread = new Thread(r, name); internalThread.setPriority(priority); } private void runWork() { Thread.yield(); while (noStopRequested) { if (yield) { Thread.yield(); } count++; for (int i = 0; i < 1000; i++) { double x = i * Math.PI / Math.E; } } } public void startRequest() { internalThread.start(); } public void stopRequest() { noStopRequested = false; } public int getCount() { return count; } public String getNameAndPriority() { return internalThread.getName() + ": priority=" + internalThread.getPriority(); } private static void runSet(boolean yield) { PriorityCompete[] pc = new PriorityCompete[3]; pc[0] = new PriorityCompete("P0", 3, yield); pc[1] = new PriorityCompete("P1", 6, yield); pc[2] = new PriorityCompete("P2", 6, yield); try { Thread.sleep(1000); } catch (InterruptedException x) { } for (int i = 0; i < pc.length; i++) { pc[i].startRequest(); } long startTime = System.currentTimeMillis(); try { Thread.sleep(10000); } catch (InterruptedException x) { } for (int i = 0; i < pc.length; i++) { pc[i].stopRequest(); } long stopTime = System.currentTimeMillis(); try { Thread.sleep(1000); } catch (InterruptedException x) { } int totalCount = 0; for (int i = 0; i < pc.length; i++) { totalCount += pc[i].getCount(); } System.out.println("totalCount=" + totalCount + ", count/ms=" + roundTo(((double) totalCount) / (stopTime - startTime), 3)); for (int i = 0; i < pc.length; i++) { double perc = roundTo(100.0 * pc[i].getCount() / totalCount, 2); System.out.println(pc[i].getNameAndPriority() + ", " + perc + "%, count=" + pc[i].getCount()); } } public static double roundTo(double val, int places) { double factor = Math.pow(10, places); return ((int) ((val * factor) + 0.5)) / factor; } public static void main(String[] args) { Runnable r = new Runnable() { public void run() { System.out.println("Run without using yield()"); System.out.println("========================="); runSet(false); System.out.println(); System.out.println("Run using yield()"); System.out.println("================="); runSet(true); } }; Thread t = new Thread(r, "Priority"); t.setPriority(Thread.MAX_PRIORITY - 1); t.start(); }
}
</source>
Thread priority information
<source lang="java">
public class GetPriority extends Object {
private static Runnable makeRunnable() { Runnable r = new Runnable() { public void run() { for (int i = 0; i < 5; i++) { Thread t = Thread.currentThread(); System.out.println("in run() - priority=" + t.getPriority() + ", name=" + t.getName()); try { Thread.sleep(2000); } catch (InterruptedException x) { // ignore } } } }; return r; } public static void main(String[] args) { System.out.println("in main() - Thread.currentThread().getPriority()=" + Thread.currentThread().getPriority()); System.out.println("in main() - Thread.currentThread().getName()=" + Thread.currentThread().getName()); Thread threadA = new Thread(makeRunnable(), "threadA"); threadA.start(); try { Thread.sleep(3000); } catch (InterruptedException x) { } System.out.println("in main() - threadA.getPriority()=" + threadA.getPriority()); }
}
</source>
Utilities to manage thread ids
<source lang="java">
/*
* JBoss, Home of Professional Open Source * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2005-2006, * @author JBoss Inc. */
/**
* Provides utilities to manage thread ids. */
public class ThreadUtil {
/** * The ID associated with the thread. */ private static final ThreadLocal THREAD_ID = new ThreadLocal(); /** * The thread id counter. */ private static long id; /** * Get the string ID for the current thread. * * @return The thread id */ public static String getThreadId() { return getThreadId(Thread.currentThread()); } /** * Get the string ID for the specified thread. * * @param thread * The thread. * @return The thread id */ public static String getThreadId(final Thread thread) { final Object id = THREAD_ID.get(); if (id != null) { return (String) id; } final String newId = getNextId(); THREAD_ID.set(newId); return newId; } /** * Get the next thread id to use. * * @return The next thread id. */ private static synchronized String getNextId() { return "TSThread:" + Long.toHexString(++id); }
}
</source>