Java Tutorial/Thread/Thread Priority — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:18, 31 мая 2010
Содержание
Change Thread Priority
- A priority tells the operating system how much resource should be given to each thread.
- A high-priority thread is scheduled to receive more time on the CPU than a low-priority thread. A method called Thread.setPriority() sets the priority of a thread. Thread class constants can be used to set these.
class CounterThread extends Thread {
String name;
public CounterThread(String name) {
super();
this.name = name;
}
public void run() {
int count = 0;
while (true) {
try {
sleep(100);
} catch (InterruptedException e) {
}
if (count == 50000)
count = 0;
System.out.println(name+":" + count++);
}
}
}
public class MainClass{
public static void main(String[] args) {
CounterThread thread1 = new CounterThread("thread1");
thread1.setPriority(10);
CounterThread thread2 = new CounterThread("thread2");
thread2.setPriority(1);
thread2.start();
thread1.start();
}
}
Demonstrate thread priorities.
class clicker implements Runnable {
int click = 0;
Thread t;
private volatile boolean running = true;
public clicker(int p) {
t = new Thread(this);
t.setPriority(p);
}
public void run() {
while (running) {
click++;
}
}
public void stop() {
running = false;
}
public void start() {
t.start();
}
}
class HiLoPri {
public static void main(String args[]) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi = new clicker(Thread.NORM_PRIORITY + 2);
clicker lo = new clicker(Thread.NORM_PRIORITY - 2);
lo.start();
hi.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
lo.stop();
hi.stop();
// Wait for child threads to terminate.
try {
hi.t.join();
lo.t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread: " + lo.click);
System.out.println("High-priority thread: " + hi.click);
}
}
Minimum and Maximum Priority Threads
public class Test {
public static void main(String[] args) {
Test t = new Test();
}
public Test() {
Runnable runner = new MyRunnable("First");
Thread t = new Thread(runner);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
runner = new MyRunnable("Second");
t = new Thread(runner);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
class MyRunnable implements Runnable {
protected String name;
public MyRunnable(String tn) {
name = tn;
}
public void run() {
while (true) {
System.out.println(name);
}
}
}
}
This class demonstrates how to set Priority
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
/**
* This class demonstrates the use of threads. The main() method is the initial
* method invoked by the interpreter. It defines and starts two more threads and
* the three threads run at the same time. Note that this class extends Thread
* and overrides its run() method. That method provides the body of one of the
* threads started by the main() method
*/
public class ThreadDemo extends Thread {
/**
* This method overrides the run() method of Thread. It provides the body for
* this thread.
*/
public void run() {
for (int i = 0; i < 5; i++)
compute();
}
/**
* This main method creates and starts two threads in addition to the initial
* thread that the interpreter creates to invoke the main() method.
*/
public static void main(String[] args) {
// Create the first thread: an instance of this class. Its body is
// the run() method above
ThreadDemo thread1 = new ThreadDemo();
// Create the second thread by passing a Runnable object to the
// Thread() construtor. The body of this thread is the run() method
// of the anonymous Runnable object below.
Thread thread2 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++)
compute();
}
});
// Set the priorities of these two threads, if any are specified
if (args.length >= 1)
thread1.setPriority(Integer.parseInt(args[0]));
if (args.length >= 2)
thread2.setPriority(Integer.parseInt(args[1]));
// Start the two threads running
thread1.start();
thread2.start();
// This main() method is run by the initial thread created by the
// Java interpreter. Now that thread does some stuff, too.
for (int i = 0; i < 5; i++)
compute();
// We could wait for the threads to stop running with these lines
// But they aren"t necessary here, so we don"t bother.
// try {
// thread1.join();
// thread2.join();
// } catch (InterruptedException e) {}
// The Java VM exits only when the main() method returns, and when all
// threads stop running (except for daemon threads--see setDaemon()).
}
// ThreadLocal objects respresent a value accessed with get() and set().
// But they maintain a different value for each thread. This object keeps
// track of how many times each thread has called compute().
static ThreadLocal numcalls = new ThreadLocal();
/** This is the dummy method our threads all call */
static synchronized void compute() {
// Figure out how many times we"ve been called by the current thread
Integer n = (Integer) numcalls.get();
if (n == null)
n = new Integer(1);
else
n = new Integer(n.intValue() + 1);
numcalls.set(n);
// Display the name of the thread, and the number of times called
System.out.println(Thread.currentThread().getName() + ": " + n);
// Do a long computation, simulating a "compute-bound" thread
for (int i = 0, j = 0; i < 1000000; i++)
j += i;
// Alternatively, we can simulate a thread subject to network or I/O
// delays by causing it to sleep for a random amount of time:
try {
// Stop running for a random number of milliseconds
Thread.sleep((int) (Math.random() * 100 + 1));
} catch (InterruptedException e) {
}
// Each thread politely offers the other threads a chance to run.
// This is important so that a compute-bound thread does not "starve"
// other threads of equal priority.
Thread.yield();
}
}