Язык программирования Java обеспечивает полный контроль над многопоточными приложениями. Благодаря этому мы можем разрабатывать многопоточные программы, которые ведут себя именно так, как нам это необходимо.
С полным списком таких методов вы можете ознакомиться в официальной документации.
Рассмотрим пример простого приложения.
Пример:
Класс ThreadControl
public class ThreadControl implements Runnable {
public Thread thread;
private String threadName;
boolean suspended = false;
ThreadControl(String name) {
threadName = name;
System.out.println("Thread " + threadName + " successfully created.");
}
public void run() {
System.out.println("Thread " + threadName + " is running...");
try {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread " + threadName + " " + i);
Thread.sleep(300);
synchronized (this) {
while (suspended) {
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " is interrupted.");
}
System.out.println("Leaving thread " + threadName + "...");
}
public void start() {
System.out.println("Starting " + threadName + " thread...");
if (thread == null) {
thread = new Thread(this, threadName);
thread.start();
}
}
void suspend() {
suspended = true;
}
synchronized void resume() {
suspended = false;
notify();
}
}
Класс ThreadControlDemo
public class ThreadControlDemo {
public static void main(String args[]) {
ThreadControl threadOne = new ThreadControl( "Thread One");
threadOne.start();
ThreadControl threadTwo = new ThreadControl( "Thread Two");
threadTwo.start();
try {
Thread.sleep(1000);
threadOne.suspend();
System.out.println("Thread One suspended...");
Thread.sleep(1000);
threadOne.resume();
System.out.println("Thread One activated");
threadTwo.suspend();
System.out.println("Thread Two suspended...");
Thread.sleep(1000);
threadTwo.resume();
System.out.println("Thread Two activated");
} catch (InterruptedException e) {
System.out.println("Main thread is interrupted...");
}
try {
System.out.println("Standing by for finishing threads.");
threadOne.thread.join();
threadTwo.thread.join();
} catch (InterruptedException e) {
System.out.println("Main thread is interrupted...");
}
System.out.println("Leaving main thread...");
}
}
В результате работы программы, мы получим, примерно, следующий результат:
/*Some System Messages*/
Thread Thread One successfully created.
Starting Thread One thread...
Thread Thread Two successfully created.
Starting Thread Two thread...
Thread Thread One is running...
Thread Thread One 1
Thread Thread Two is running...
Thread Thread Two 1
Thread Thread One 2
Thread Thread Two 2
Thread Thread One 3
Thread Thread Two 3
Thread Thread One 4
Thread Thread Two 4
Thread One suspended...
Thread Thread Two 5
Leaving thread Thread Two...
Thread One activated
Thread Thread One 5
Thread Two suspended...
Leaving thread Thread One...
Thread Two activated
Standing by for finishing threads.
Leaving main thread...
В этом разделе мы ознакомились с основами управления многопоточными приложениями.