How to use thread functions for thread management in Java
With the continuous improvement of computer processing power, multi-threaded programming is becoming more and more important. In Java, we can manage threads through thread functions. A thread function is a special function that executes in a separate running thread. This article will introduce how to use thread functions for thread management in Java and provide specific code examples.
By inheriting the Thread class:
class MyThread extends Thread { public void run() { // 线程逻辑 } } // 创建线程并启动 MyThread thread = new MyThread(); thread.start();
By implementing the Runnable interface:
class MyRunnable implements Runnable { public void run() { // 线程逻辑 } } // 创建线程并启动 Thread thread = new Thread(new MyRunnable()); thread.start();
class MyThread extends Thread { public void run() { try { // 线程逻辑 } catch (InterruptedException e) { e.printStackTrace(); } } } // 创建线程并启动 MyThread thread = new MyThread(); thread.start(); // 暂停线程 thread.sleep(1000); // 中断线程 thread.interrupt(); // 等待线程结束 thread.join(); // 判断线程是否还在运行 boolean isRunning = thread.isAlive();
class Counter { private int count = 0; private Object lock = new Object(); public void increment() { synchronized (lock) { count++; } } public int getCount() { return count; } } class MyThread extends Thread { private Counter counter; public MyThread(Counter counter) { this.counter = counter; } public void run() { for (int i = 0; i < 1000; i++) { counter.increment(); } } } // 创建计数器 Counter counter = new Counter(); // 创建线程并启动 MyThread thread1 = new MyThread(counter); MyThread thread2 = new MyThread(counter); thread1.start(); thread2.start(); // 等待线程结束 thread1.join(); thread2.join(); // 输出结果 System.out.println(counter.getCount());
ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) { executor.execute(new Runnable() { public void run() { // 线程逻辑 } }); } // 关闭线程池 executor.shutdown();
Through the thread pool, we can reuse threads, reduce the cost of thread creation and destruction, and improve program performance.
Summary
Through thread functions, we can easily create and manage threads and implement multi-threaded programming. When writing a multi-threaded program, you need to pay attention to the life cycle and synchronization mechanism of the thread to ensure the correct execution of the thread. If you need to improve performance and manage threads, you can use a thread pool to manage thread resources. Through continuous learning and practice, we can better master the skills of using thread functions and write efficient and reliable multi-threaded programs.
The above is the detailed content of How to use thread functions for thread management in Java. For more information, please follow other related articles on the PHP Chinese website!