Запуск потоков в java
Как запустить несколько потоков в java одновременно?
Как запустить несколько потоков в java одновременно?
В майнкрафте же это делается. Несколько сразу
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger value = new AtomicInteger();
Thread incValueThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
value.getAndIncrement();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread decValueThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
value.getAndDecrement();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread checkThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
if (value.get() == 3) {
System.exit(0);
}
}
});
Thread showThread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Current value: " + value);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
List < Thread > threads = new ArrayList < > ();
threads.add(incValueThread);
threads.add(decValueThread);
threads.add(checkThread);
threads.add(showThread);
threads.forEach(Thread::start);
}
}