java中Thread的示例分析

发布时间:2021-09-10 11:00:57 作者:小新
来源:亿速云 阅读:138
# Java中Thread的示例分析

## 1. 线程基础概念

在Java中,`Thread`类是用于创建和管理线程的核心类。每个线程代表一个独立的执行路径,允许程序实现并发执行。

### 1.1 线程生命周期
- **NEW**: 通过`new Thread()`创建但未启动
- **RUNNABLE**: 调用`start()`后进入可运行状态
- **BLOCKED**: 等待监视器锁(同步块)
- **WTING**: 无限期等待其他线程操作
- **TIMED_WTING**: 带超时的等待
- **TERMINATED**: 执行完成或异常终止

## 2. 创建线程的两种方式

### 2.1 继承Thread类

```java
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread running: " + getName());
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();  // 启动线程
    }
}

特点: - 简单直接 - 由于Java单继承限制,扩展性较差

2.2 实现Runnable接口

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Thread running: " + 
            Thread.currentThread().getName());
    }
}

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

优势: - 避免单继承限制 - 更适合资源共享场景

3. 线程控制示例

3.1 基础控制方法

Thread t = new Thread(() -> {
    try {
        Thread.sleep(1000);  // 暂停1秒
        System.out.println("After sleep");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

t.start();
t.join();  // 等待线程结束
System.out.println("Main thread continues");

3.2 线程优先级示例

Thread high = new Thread(() -> {
    for (int i = 0; i < 5; i++) {
        System.out.println("High priority");
    }
});
high.setPriority(Thread.MAX_PRIORITY);

Thread low = new Thread(() -> {
    for (int i = 0; i < 5; i++) {
        System.out.println("Low priority");
    }
});
low.setPriority(Thread.MIN_PRIORITY);

low.start();
high.start();

4. 线程同步示例

4.1 同步方法

class Counter {
    private int count = 0;
    
    public synchronized void increment() {
        count++;
    }
    
    public int getCount() {
        return count;
    }
}

4.2 同步块

public void add(int value) {
    synchronized(this) {
        this.count += value;
    }
}

4.3 使用Lock接口

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SafeCounter {
    private final Lock lock = new ReentrantLock();
    private int count = 0;
    
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}

5. 线程间通信

5.1 wait/notify机制

class Message {
    private String msg;
    
    public synchronized void set(String msg) {
        this.msg = msg;
        notify();  // 唤醒等待线程
    }
    
    public synchronized String get() {
        while (msg == null) {
            try {
                wait();  // 释放锁并等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String temp = msg;
        msg = null;
        return temp;
    }
}

6. 线程池示例

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread("Task " + i);
            executor.execute(worker);
        }
        
        executor.shutdown();
        while (!executor.isTerminated()) {}
        
        System.out.println("All tasks completed");
    }
}

class WorkerThread implements Runnable {
    private String task;
    
    public WorkerThread(String task) {
        this.task = task;
    }
    
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() 
            + " processing " + task);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

7. 常见问题与最佳实践

  1. 避免直接使用Thread类:推荐使用线程池(ExecutorService)
  2. 正确处理InterruptedException:不要忽略中断异常
  3. 减少同步范围:同步块应尽量小
  4. 优先使用并发工具类:如CountDownLatch, CyclicBarrier
  5. 注意线程安全集合:使用ConcurrentHashMap等线程安全集合

结语

Java线程编程是并发处理的核心技术,正确理解Thread类的使用方法和线程同步机制,对于开发高性能、线程安全的应用程序至关重要。随着Java版本更新,更推荐使用java.util.concurrent包中的高级API来处理并发问题。 “`

注:本文约1100字,涵盖了Java线程的基础使用、同步控制、线程通信和线程池等核心内容,采用Markdown格式编写,包含代码示例和结构化说明。

推荐阅读:
  1. C#中多线程之Thread类的示例分析
  2. 如何使用Java Thread中Sleep()

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java thread

上一篇:SSH安全性的加强步骤

下一篇:怎么通过重启路由的方法切换IP地址

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》