0
点赞
收藏
分享

微信扫一扫

Java一分钟:多线程编程初步:Thread类与Runnable接口

多线程是Java中实现并发执行任务的关键特性。本文将简要介绍Java中创建线程的两种方式:继承Thread类和实现Runnable接口,并讨论常见问题、易错点及其避免策略。 image.png

1. 创建线程

继承Thread类

创建一个新类继承Thread,重写run()方法,然后创建该类的实例并调用start()启动线程。

public class MyThread extends Thread {
@Override
public void run() {
// 线程执行逻辑
}

public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}

实现Runnable接口

创建一个实现Runnable接口的类,重写run()方法,然后将Runnable实例传给Thread构造器。

public class MyRunnable implements Runnable {
@Override
public void run() {
// 线程执行逻辑
}

public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}

2. 常见问题与避免策略

  • 资源浪费:每个线程都占用一定的系统资源,过度创建线程可能导致资源浪费。合理评估线程数量,使用线程池管理线程。
  • 线程安全:多个线程共享数据可能导致数据不一致。使用synchronized关键字、volatile变量或Atomic类保证线程安全。
  • 死锁:多个线程相互等待对方释放资源,导致所有线程都无法继续。避免循环等待,使用超时或中断机制。
  • 优先级问题:线程优先级可能导致不公平的执行顺序。谨慎设置线程优先级,避免依赖优先级进行调度。

3. 示例:线程通信

public class ThreadCommunication {
private int count = 0;

public static void main(String[] args) {
ThreadCommunication tc = new ThreadCommunication();
Thread producer = new Thread(() -> tc.produce());
Thread consumer = new Thread(() -> tc.consume());
producer.start();
consumer.start();
}

synchronized void produce() {
for (int i = 0; i < 10; i++) {
count++;
System.out.println(Produced: + count);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

synchronized void consume() {
for (int i = 0; i < 10; i++) {
if (count == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
count--;
System.out.println(Consumed: + count);
notifyAll();
}
}
}
}

以上代码展示了生产者-消费者模型,使用synchronizedwait()notifyAll()实现线程间通信。

总结,理解和掌握线程的创建方式,以及多线程编程中的问题和解决策略,是编写高效并发程序的基础。在实际开发中,合理使用线程池、同步机制和并发工具类,可以避免许多并发问题,提升程序性能。

举报

相关推荐

0 条评论