Java 多线程使用详解

Java 多线程使用详解

多线程是 Java 中实现并发编程的重要机制,能够充分利用多核处理器资源,提高程序的执行效率。下面我将通过实际案例和应用场景,详细介绍 Java 多线程的使用。

1. 线程创建的几种方式

1.1 继承 Thread 类

public class MyThread extends Thread {
   
    @Override
    public void run() {
   
        System.out.println("当前线程名称:" + Thread.currentThread().getName());
        // 线程执行的任务
        for (int i = 0; i < 5; i++) {
   
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
    
    public static void main(String[] args) {
   
        // 创建线程对象
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        
        // 设置线程名称
        thread1.setName("线程1");
        thread2.setName("线程2");
        
        // 启动线程
        thread1.start();
        thread2.start();
    }
}

1.2 实现 Runnable 接口(推荐)

public class MyRunnable implements Runnable {
   
    @Override
    public void run() {
   
        System.out.println("当前线程名称:" + Thread.currentThread().getName());
        // 线程执行的任务
        for (int i = 0; i < 5; i++) {
   
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
    
    public static void main(String[] args) {
   
        // 创建任务对象
        MyRunnable myRunnable = new MyRunnable();
        
        // 创建线程对象,并将任务对象作为参数传入
        Thread thread1 = new Thread(myRunnable, "线程1");
        Thread thread2 = new Thread(myRunnable, "线程2");
        
        // 启动线程
        thread1.start();
        thread2.start();
    }
}

1.3 实现 Callable 接口(可获取返回值)

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;

public class MyCallable implements Callable<Integer> {
   
    @Override
    public Integer call() throws Exception {
   
        System.out.println("当前线程名称:" + Thread.currentThread().getName());
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
   
            sum += i;
        }
        return sum;
    }
    
    public static void main(String[] args) {
   
        // 创建任务对象
        MyCallable myCallable = new MyCallable();
        
        // 使用FutureTask包装Callable对象
        FutureTask<Integer> futureTask1 = new FutureTask<>(myCallable);
        FutureTask<Integer> futureTask2 = new FutureTask<>(myCallable);
        
        // 创建线程对象
        Thread thread1 = new Thread(futureTask1, "线程1");
        Thread thread2 = new Thread(futureTask2, "线程2");
        
        // 启动线程
        thread1.start();
        thread2.start();
        
        try {
   
            // 获取线程执行结果
            System.out.println("线程1结果:" + futureTask1.get());
            System.out.println("线程2结果:" + futureTask2.get());
        } catch (InterruptedException | ExecutionException e) {
   
            e.printStackTrace();
        }
    }
}

1.4 使用 Lambda 表达式(Java 8+)

public class LambdaThread {
   
    public static void main(String[] args) {
   
        // 使用Lambda表达式创建Runnable实例
        Thread thread1 = new Thread(() -> {
   
            System.out.println("当前线程名称:" + Thread.currentThread().getName());
            for (int i = 0; i < 5; i++) {
   
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }, "Lambda线程1");
        
        thread1.start();
    }
}

2. 线程生命周期和状态

Java 线程有以下几种状态:

  • NEW(新建)
  • RUNNABLE(可运行)
  • BLOCKED(阻塞)
  • WAITING(等待)
  • TIMED_WAITING(计时等待)
  • TERMINATED(终止)

在这里插入图片描述

3. 线程同步机制

3.1 synchronized 关键字

public class SynchronizedExample {
   
    private int count = 0;
    
    // 同步方法
    public synchronized void increment() {
   
        count++;
    }
    
    // 同步代码块
    public void incrementBlock() {
   
        synchronized(this) {
   
            count++;
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
   
        SynchronizedExample example = new SynchronizedExample();
        
        Thread thread1 = new Thread(() -> {
   
            for (int i = 0; i < 10000; i++) {
   
                example.increment();
            }
        });
        
        Thread thread2 = new Thread(() -> {
   
            for (int i = 0; i < 10000; i++) {
   
                example.increment();
            }
        });
        
        thread1.start();
        thread2.start();
        
        thread1.join();
        thread2.join();
        
        System.out.println("最终计数: " + example.count);
    }
}

3.2 Lock 接口

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

public class LockExample {
   
    private int count = 0;
    private final Lock lock = new ReentrantLock();
    
    public void increment() {
   
        lock.lock();
        try {
   
            count++;
        } finally {
   
            lock.unlock(); // 确保锁被释放
        }
    }
    
    pub
1. 建立三个线程,并且同时运行它们。当运行时输出线程的名称。 实验步骤: (1)、创建类sy6_1 (2)、创建三个线程,调用start()方法启动这三个线程 (3)、保存文件,调试并编译运行程序。 参考程序运行效果: 2. 实现3个类:Storage、Counter和Printer。 Storage类应存储整数。 Counter应创建线程,线程从0开始计数(0,1,2,3…)并将每个值存储到Storage类中。 Printer类应创建一个线程,线程读取Storage类中的值并打印值。编写程序创建Storage类的实例,并创建一个Counter对象和Printer对象操作此实例。 实验步骤: (1)、创建三个类Counter, Printer,Storage (2)、创建TestCounter类,在该类中定义main函数,在main函数中定义Storage对象、Counter对象和 Printer对象,创建Counter线程和Printer线程并启动 (3)、保存文件,调试并编译运行程序。 参考程序运行效果: 3. 修改实验1第2题的程序,添加适当代码,以确保每个数字都恰好只被打印一次。 实验步骤: (1)、创建三个类Counter, Printer,Storage (2)、 创建TestCounter类,在该类中定义main函数,在main函数中定义Storage对象、Counter1对象和 Printer对象,创建Counter线程和Printer线程并启动 (3)、在定义Storage类中的setValue(int i) 和getValue ()方法时使用synchronized关键字,将其定义为同步方法 (4)、保存文件,调试并编译运行程序。 参考程序运行效果:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qzw1210

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值