Java Thread

Thread Java

Java Thread ""

Java

  1. Thread
  2. Runnable

Thread

// 1 Thread
class MyThread extends Thread {
    public void run() {
        System.out.println("");
    }
}

// 2 Runnable
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("");
    }
}

public class Main {
    public static void main(String[] args) {
        //
        MyThread thread1 = new MyThread();
        thread1.start();
       
        //
        Thread thread2 = new Thread(new MyRunnable());
        thread2.start();
    }
}

Java

  • NEW start()
  • RUNNABLE CPU
  • BLOCKED
  • WAITING
  • TIMED_WAITING
  • TERMINATED

Thread

Thread thread = new Thread(() -> {
    System.out.println("");
});

thread.start();  //
thread.join();   //
thread.sleep(1000); // 1

thread.setPriority(Thread.MAX_PRIORITY);  // (10)
thread.setPriority(Thread.NORM_PRIORITY); // (5)
thread.setPriority(Thread.MIN_PRIORITY);  // (1)

thread.interrupt(); //

//
if (Thread.interrupted()) {
    //
}

synchronized

class Counter {
    private int count = 0;
   
    public synchronized void increment() {
        count++;
    }
}

Lock

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Counter {
    private int count = 0;
    private Lock lock = new ReentrantLock();
   
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}

Thread

Thread

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
       
        for (int i = 0; i < 10; i++) {
            executor.execute(() -> {
                System.out.println("");
            });
        }
       
        executor.shutdown();
    }
}

  1. Runnable
  2. volatile
  3. Java (java.util.concurrent)

Thread Java