java如何使用thread
使用Thread类创建线程
在Java中,可以通过继承Thread类并重写run()方法来创建线程。定义一个类继承Thread,并在run()方法中编写线程执行的代码。创建该类的实例并调用start()方法启动线程。
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口创建线程
另一种方式是实现Runnable接口,并将其实例传递给Thread类的构造函数。这种方式更灵活,因为Java不支持多重继承,但可以实现多个接口。
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Lambda表达式简化Runnable实现
对于简单的任务,可以使用Lambda表达式简化Runnable的实现,避免创建单独的类。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running");
});
thread.start();
}
}
线程的常用方法
Thread类提供了多个方法来控制线程的行为:
start():启动线程,调用run()方法。sleep(long millis):使线程休眠指定的毫秒数。join():等待线程终止。interrupt():中断线程。
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
System.out.println("Thread woke up");
} catch (InterruptedException e) {
System.out.println("Thread was interrupted");
}
});
thread.start();
thread.join();
System.out.println("Main thread finished");
}
}
线程同步与锁
多线程环境下,共享资源的访问需要同步以避免竞态条件。可以使用synchronized关键字或ReentrantLock实现同步。
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) throws InterruptedException {
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();
t1.join();
t2.join();
System.out.println("Final 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(3);
for (int i = 0; i < 5; i++) {
executor.submit(() -> {
System.out.println("Task executed by " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
线程间的通信
线程间可以通过wait()、notify()和notifyAll()方法实现通信。这些方法必须在synchronized块中调用。

class Message {
private String msg;
public synchronized void setMessage(String msg) {
this.msg = msg;
notify();
}
public synchronized String getMessage() throws InterruptedException {
if (msg == null) {
wait();
}
return msg;
}
}
public class Main {
public static void main(String[] args) {
Message message = new Message();
Thread producer = new Thread(() -> {
message.setMessage("Hello, Thread!");
});
Thread consumer = new Thread(() -> {
try {
System.out.println(message.getMessage());
} catch (InterruptedException e) {
e.printStackTrace();
}
});
consumer.start();
producer.start();
}
}






