如何在java中实现线程
实现线程的两种主要方法
在Java中,可以通过继承Thread类或实现Runnable接口来创建线程。
继承Thread类
通过继承Thread类并重写run()方法来定义线程的执行逻辑。创建子类实例后调用start()方法启动线程。
class MyThread extends Thread {
public void run() {
System.out.println("Thread running by extending Thread class");
}
}
public class Main {
public static void main(String args[]) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口
实现Runnable接口并实现run()方法。将Runnable实例传递给Thread构造函数来创建线程实例。
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running by implementing Runnable interface");
}
}
public class Main {
public static void main(String args[]) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Lambda表达式简化Runnable实现
Java 8以后可以用Lambda表达式简化Runnable接口的实现。
public class Main {
public static void main(String args[]) {
Thread thread = new Thread(() -> {
System.out.println("Thread running using Lambda expression");
});
thread.start();
}
}
线程优先级和名称设置
可以设置线程的优先级和名称来管理线程执行。
Thread thread = new Thread(() -> {
System.out.println("Running thread: " + Thread.currentThread().getName());
});
thread.setName("MyThread");
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
线程同步
当多个线程访问共享资源时,需要使用同步机制。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String args[]) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + counter.getCount());
}
}
线程池的使用
使用ExecutorService可以更方便地管理线程池。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String args[]) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("All threads finished");
}
}
class WorkerThread implements Runnable {
private String message;
public WorkerThread(String s) {
this.message = s;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " processing " + message);
processMessage();
System.out.println(Thread.currentThread().getName() + " finished");
}
private void processMessage() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}




