Sobes.tech
Junior — Middle

What key principles should be considered when creating a new thread in a program?

sobes.tech AI

Answer from AI

When creating a new thread in Java, it is important to consider the following key principles:

  • Thread Safety: ensure that access to shared resources is synchronized to avoid race conditions.
  • Using the Runnable interface or extending Thread: it is preferable to implement Runnable to separate logic from thread management.
  • Managing the thread lifecycle: properly start, stop if necessary, and release resources.
  • Avoiding deadlocks and blocking: design code to minimize lock holding time and prevent mutual blocking.
  • Using modern tools from java.util.concurrent: for example, ExecutorService for managing thread pools instead of manual thread creation.

Example of creating a thread with Runnable:

public class MyTask implements Runnable {
    @Override
    public void run() {
        System.out.println("Thread started");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyTask());
        thread.start();
    }
}