import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;
public class ThreadCreationDemo {
public static void main(String[] args) {
var counter = new AtomicInteger();
while (true) {
new Thread(() -> {
int count = counter.incrementAndGet();
System.out.println("count = " + count);
LockSupport.park();
}).start();
}
}
}
count = 108108
[309.711s][warning][os,thread] Failed to start thread "Unknown thread" - _beginthreadex failed (EINVAL) for attributes: stacksize: default, flags: CREATE_SUSPENDED STACK_SIZE_PARAM_IS.
[309.711s][warning][os,thread] Failed to start the native thread for java.lang.Thread "Thread-108108"
Exception in thread "main" java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached
at java.base/java.lang.Thread.start0(Native Method)
at java.base/java.lang.Thread.start(Thread.java:1518)
at ThreadCreationDemo.main(ThreadCreationDemo.java:13)
public class HeapSize {
public static void main(String[] args) {
long totalMemory = Runtime.getRuntime().totalMemory() / 1024 / 1024;
long maxMemory = Runtime.getRuntime().maxMemory() / 1024 / 1024;
System.out.println("Начальный: " + totalMemory + " MB");
System.out.println("Максимальный: " + maxMemory + " MB");
}
}
public interface ThreadPool {
void submit(Runnable unitOfWork);
void shutdown();
}
import java.util.LinkedList;
import java.util.List;
class MyThreadPool implements ThreadPool {
private final List<Runnable> tasks = new LinkedList<>();
private volatile boolean running = true;
public MyThreadPool(int poolSize) {
for (int i = 0; i < poolSize; i++) {
var workerThread = new WorkerThread("worker-" + i);
workerThread.start();
}
}
@Override
public void submit(Runnable unitOfWork) {
synchronized (tasks) {
tasks.add(unitOfWork);
tasks.notifyAll();
}
}
@Override
public void shutdown() {
this.running = false;
}
private Runnable take() throws InterruptedException {
synchronized (tasks) {
while (tasks.isEmpty()) {
tasks.wait();
}
return tasks.removeFirst();
}
}
private class WorkerThread extends Thread {
public WorkerThread(String name) {
super(name);
}
@Override
public void run() {
while (running) {
try {
Runnable currentTask = take();
currentTask.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Playground {
public static void main(String[] args) throws InterruptedException {
var pool = new MyThreadPool(10);
for (int i = 0; i < 100; i++) {
pool.submit(() -> System.out.println("Running inside: " +
Thread.currentThread()));
}
}
}