您好,登录后才能下订单哦!
在Java编程中,多线程是一个非常重要的概念。多线程允许程序同时执行多个任务,从而提高程序的效率和响应速度。Java提供了丰富的多线程API,使得开发者可以轻松地创建和管理线程。本文将详细介绍Java多线程中常用的方法,帮助读者更好地理解和应用多线程编程。
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();
}
}
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();
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable<String> {
public String call() {
return "Thread is running";
}
}
public class Main {
public static void main(String[] args) throws Exception {
FutureTask<String> task = new FutureTask<>(new MyCallable());
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());
}
}
线程对象被创建后,处于新建状态。
调用start()
方法后,线程进入就绪状态,等待CPU调度。
线程获得CPU资源后,进入运行状态,执行run()
方法。
线程由于某些原因(如等待I/O操作、调用sleep()
方法等)暂时停止执行,进入阻塞状态。
线程执行完run()
方法后,进入终止状态。
启动线程,使其进入就绪状态。
thread.start();
线程执行的主体方法。
public void run() {
// 线程执行的代码
}
使当前线程暂停执行指定的时间(毫秒)。
Thread.sleep(1000); // 暂停1秒
等待该线程终止。
thread.join(); // 等待thread线程终止
暂停当前线程,让出CPU资源给其他线程。
Thread.yield();
中断线程。
thread.interrupt();
判断线程是否被中断。
if (thread.isInterrupted()) {
// 线程被中断
}
设置线程的优先级。
thread.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级
获取线程的优先级。
int priority = thread.getPriority();
设置线程为守护线程。
thread.setDaemon(true);
判断线程是否为守护线程。
if (thread.isDaemon()) {
// 线程是守护线程
}
获取当前线程的引用。
Thread currentThread = Thread.currentThread();
获取线程的名称。
String name = thread.getName();
设置线程的名称。
thread.setName("MyThread");
获取线程的ID。
long id = thread.getId();
获取线程的状态。
Thread.State state = thread.getState();
判断线程是否处于活动状态。
if (thread.isAlive()) {
// 线程处于活动状态
}
用于修饰方法或代码块,确保同一时间只有一个线程执行该代码。
synchronized void method() {
// 同步代码
}
使当前线程等待,直到其他线程调用notify()
或notifyAll()
方法。
synchronized (obj) {
obj.wait();
}
唤醒在此对象监视器上等待的单个线程。
synchronized (obj) {
obj.notify();
}
唤醒在此对象监视器上等待的所有线程。
synchronized (obj) {
obj.notifyAll();
}
可重入锁,提供比synchronized
更灵活的锁机制。
ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
// 同步代码
} finally {
lock.unlock();
}
与ReentrantLock
配合使用,提供更细粒度的线程通信。
Condition condition = lock.newCondition();
condition.await(); // 等待
condition.signal(); // 唤醒
用于管理线程池的框架。
Executor executor = Executors.newFixedThreadPool(10);
executor.execute(new Runnable() {
public void run() {
// 任务代码
}
});
自定义线程池。
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5, // 核心线程数
10, // 最大线程数
60, // 空闲线程存活时间
TimeUnit.SECONDS, // 时间单位
new LinkedBlockingQueue<>() // 任务队列
);
executor.execute(new Runnable() {
public void run() {
// 任务代码
}
});
提供创建线程池的工厂方法。
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Runnable() {
public void run() {
// 任务代码
}
});
支持定时任务的线程池。
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
executor.schedule(new Runnable() {
public void run() {
// 任务代码
}
}, 10, TimeUnit.SECONDS); // 10秒后执行
线程安全的HashMap。
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("key", "value");
线程安全的ArrayList。
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("element");
线程安全的队列。
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
queue.put("element");
String element = queue.take();
使用PipedInputStream
和PipedOutputStream
进行线程间通信。
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
new Thread(() -> {
try {
out.write("Hello".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
System.out.println(new String(buffer, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
}).start();
使用Semaphore
控制资源的访问。
Semaphore semaphore = new Semaphore(2);
new Thread(() -> {
try {
semaphore.acquire();
// 访问资源
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}).start();
等待多个线程完成。
CountDownLatch latch = new CountDownLatch(3);
new Thread(() -> {
// 任务代码
latch.countDown();
}).start();
latch.await(); // 等待所有线程完成
等待多个线程到达某个屏障点。
CyclicBarrier barrier = new CyclicBarrier(3);
new Thread(() -> {
try {
// 任务代码
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
两个线程交换数据。
Exchanger<String> exchanger = new Exchanger<>();
new Thread(() -> {
try {
String data = exchanger.exchange("Hello");
System.out.println(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
String data = exchanger.exchange("World");
System.out.println(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
使用AtomicInteger
等原子类保证线程安全。
AtomicInteger atomicInteger = new AtomicInteger(0);
atomicInteger.incrementAndGet();
保证变量的可见性。
volatile boolean flag = true;
为每个线程提供独立的变量副本。
ThreadLocal<String> threadLocal = new ThreadLocal<>();
threadLocal.set("Hello");
String value = threadLocal.get();
Java多线程编程是一个复杂而强大的领域,掌握常用的多线程方法和技巧对于编写高效、稳定的并发程序至关重要。本文详细介绍了Java多线程中常用的方法,包括线程的创建与启动、生命周期、常用方法、线程同步、线程池、并发集合、线程间通信以及线程安全等内容。希望本文能帮助读者更好地理解和应用Java多线程编程。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。