Читаем Основы программирования на Java полностью

Thread ct = Thread.currentThread();

System.out.println("currentThread: " + ct);

Thread t = new Thread(this, "Demo Thread");

System.out.println("Thread created: " +1);

t.start();

try {

Thread.sleep(3000);

}

catch (InterruptedException e) {

System.out.println("прерывание");

}

System.out.println("Выход из main подпроцесса");

}

public void run() {

try {

for (int i = 5; i > 0; i--) {

System.out.println("" + i);

Thread.sleep(l000);

}

}

catch (InterruptedException e) {

System.out.println("child прерван");

}

System.out.println("Выход из child подпроцесса ");

}

public static void main(String args[]) {

new ThreadDemo();

}

}

Обратите внимание на то, что цикл внутри метода run выглядит точно так же, как и в предыдущем примере, только на этот раз он выполняется в другом подпроцессе. Подпроцесс main с помощью оператора new Thread(this, "Demo Thread") создает новый объект класса Thread, причем первый параметр конструктора — this — указывает, что мы хотим вызвать метод run текущего объекта. Затем мы вызываем метод start, который запускает подпроцесс, выполняющий метод run. После этого основной подпроцесс (main) переводится в состояние ожидания на три секунды, затем выводит сообщение и завершает работу. Второй подпроцесс — «Demo Thread» — при этом по-прежнему выполняет итерации в цикле метода run до тех пор, пока значение счетчика цикла не уменьшится до нуля. Ниже показано, как выглядит результат работы этой программы после того, как она отработает 5 секунд.

С:\> java ThreadDemo

Thread created: Thread[Demo Thread,5,main]

5

4

3

Выход из main подпроцесса

2

1

Выход из child подпроцесса

10.4. Приоритеты подпроцессов


Если вы хотите добиться от Java предсказуемого, независимого от платформы поведения, вам следует проектировать свои подпроцессы таким образом, чтобы они по своей воле освобождали процессор. Ниже приведен пример с двумя подпроцессами с различными приоритетами, которые не ведут себя одинаково на различных платформах. Приоритет одного из подпроцессов с помощью вызова setPriority устанавливается на два уровня выше Thread. NORM_PRIORITY, то есть умалчиваемого приоритета. У другого подпроцесса приоритет, наоборот, на два уровня ниже. Оба этих подпроцесса запускаются и работают в течение 10 секунд. Каждый из них выполняет цикл, в котором увеличивается значение переменной-счетчика. Через десять секунд после их запуска основной подпроцесс останавливает их работу, присваивая условию завершения цикла while значение «true», и выводит значения счетчиков, показывающих, сколько итераций цикла успел выполнить каждый из подпроцессов.

class Clicker implements Runnable {

int click = 0;

private Thread t;

private 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.M AX_PRIORIT Y);

clicker hi = new clicker(Thread.NORM_PRIORITY + 2);

clicker lo = new clicker(Thread.NORM_PRIORITY - 2);

lo.start();

hi.start();

try {

Thread.sleep(l0000)

}

catch (Exception e) {}

lo.stop(); hi.stop();

System.out.println(lo.click +” vs.” + hi.click);

}

}

По значениям, фигурирующим в итоге, можно заключить, что подпроцессу с низким приоритетом достается меньше на 25 процентов времени процессора:

C:\>java HiLoPri

304300 vs. 4066666

10.5. Синхронизация


Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных