How to use Thread in Java, specific code examples
The following is a code example of using two methods to create a thread:
// 继承Thread类 class MyThread extends Thread { public void run(){ // 线程执行的代码 } } // 实现Runnable接口 class MyRunnable implements Runnable { public void run(){ // 线程执行的代码 } } // 创建线程并启动 public static void main(String[] args){ // 创建继承Thread类的线程 MyThread thread1 = new MyThread(); thread1.start(); // 创建实现Runnable接口的线程 MyRunnable runnable = new MyRunnable(); Thread thread2 = new Thread(runnable); thread2.start(); }
In the above code, the thread created by inheriting the Thread class directly calls the start method to start the thread. , and a thread created by implementing the Runnable interface needs to first create a Thread object, pass the object that implements the Runnable interface as a parameter to the Thread constructor, and then call the start method of the Thread object to start the thread.
The following is a simple example showing the life cycle of a thread:
class MyThread extends Thread { public void run(){ System.out.println("线程执行中"); try { Thread.sleep(1000); // 线程等待1秒 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程执行结束"); } } public static void main(String[] args){ MyThread thread = new MyThread(); System.out.println("线程状态:" + thread.getState()); // 输出线程状态为New thread.start(); System.out.println("线程状态:" + thread.getState()); // 输出线程状态为Runnable // 等待线程执行结束 try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程状态:" + thread.getState()); // 输出线程状态为Terminated }
In the above code, after a new thread is created and started, the status of the thread is first output is New, and then the output status is Runnable. After calling the thread.join() method and waiting for the thread execution to end, the final output status is Terminated.
Java provides mechanisms such as the synchronized keyword and Lock interface to achieve thread synchronization and mutual exclusion. The following is an example of using the synchronized keyword for thread synchronization:
class Counter { private int count = 0; // 线程安全的方法 public synchronized void increment(){ count++; } public int getCount(){ return count; } } public static void main(String[] args){ Counter counter = new Counter(); Runnable runnable = () -> { for(int i=0; i<10000; i++){ counter.increment(); } }; Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("计数器的值:" + counter.getCount()); // 输出:20000 }
In the above code example, a thread-safe Counter class is defined, in which the increment method uses the synchronized keyword to synchronize shared data. Two threads called the Counter object at the same time. Each thread performed 10,000 increment operations on count, and finally output the correct result of 20,000.
The following is a sample code that shows how to interrupt a thread:
class MyThread extends Thread { public void run(){ while(!isInterrupted()){ System.out.println("线程运行中"); try { Thread.sleep(1000); // 线程等待1秒 } catch (InterruptedException e) { e.printStackTrace(); break; } } System.out.println("线程中断"); } } public static void main(String[] args){ MyThread thread = new MyThread(); thread.start(); try { Thread.sleep(5000); // 主线程等待5秒 } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); // 中断线程 }
In the above code, after a new thread is created and started, the main thread waits for 5 seconds Then the child thread is interrupted.
Summary:
This article introduces the use of the Thread class in Java and provides some specific code examples. You can create a thread by inheriting the Thread class or implementing the Runnable interface, and start the thread by calling the start method. Understanding the thread life cycle and the concepts of thread synchronization and mutual exclusion is very important for writing robust multi-threaded programs. At the same time, understanding how to interrupt threads is also an important knowledge point in multi-threaded programming. Mastering these contents can help developers use multi-threaded programming to improve program efficiency and concurrency.
The above is the detailed content of How to use threads in Java. For more information, please follow other related articles on the PHP Chinese website!