Java线程知识点简介

1. Java线程基础

什么是线程?简单来说,线程是程序执行的最小单位,它是进程中的一个单一顺序控制流程,多个线程可以并发执行,利用CPU的多核特性,提高程序的执行效率。

Java中实现线程主要有两种方式:继承Thread类和实现Runnable接口。

1.1 继承Thread类

当你的类继承了Thread类,你可以通过覆盖其run()方法来定义线程执行的代码。

public class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running");
    }
}

public class TestThread {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start();
        System.out.println("Main thread running");
    }
}

在这个例子中,MyThread类继承了Thread类,并覆盖了run()方法。在main方法中,我们创建了MyThread的实例并调用了start()方法,这会导致run()方法在一个新的线程中执行。

1.2 实现Runnable接口

另一种实现线程的方式是实现Runnable接口,然后将其实例传递给Thread类的构造函数。这种方式更加灵活,因为Java不支持多重继承。

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable running");
    }
}

public class TestRunnable {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
        System.out.println("Main thread running");
    }
}

2. 线程的生命周期

Java线程的生命周期包括以下几个状态:新建、就绪、运行、阻塞、死亡。

  • 新建(New):当你创建了线程的实例,但还没有调用start()方法。
  • 就绪(Runnable):调用start()方法后,线程被放到执行队列等待CPU调度。
  • 运行(Running):当线程获得CPU执行时间时,其run()方法体将被执行。
  • 阻塞(Blocked):在等待监视器锁或调用sleep()、join()、wait()等方法时,线程将进入阻塞状态。
  • 死亡(Dead):线程的run()方法执行完毕或因异常退出run()方法后,线程将终止。

3. 线程同步

如果多个线程访问同一资源而没有适当的同步,那么程序可能会产生不可预料的结果。我们可以使用synchronized关键字来控制对共享资源的访问。

3.1 synchronized方法
public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

在这个例子中,我们通过在方法上添加synchronized关键字来保证increment()和getCount()方法在多线程环境中是线程安全的。

3.2 synchronized块

如果你只需要对对象中的某部分代码进行同步,可以使用synchronized块。

public class BlockSync {
    private int count = 0;

    public void increment() {
        synchronized(this) {
            count++;
        }
    }
}

4. 线程通信

线程间的通信是多线程编程中的另一个重要话题。线程可以通过wait()、notify()和notifyAll()方法进行通信。这些方法必须在同步块或同步方法中调用。

4.1 wait()和notify()
public class WaitNotifyExample {
    public synchronized void before() {
        System.out.println("before");
        notify();
    }

    public synchronized void after() {
        try {
            wait();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        System.out.println("after");
    }
}

public class TestWN {
    public static void main(String[] args) {
        WaitNotifyExample example = new WaitNotifyExample();
        Thread t1 = new Thread(() -> {
            example.after();
        });
        Thread t2 = new Thread(() -> {
            example.before();
        });
        t1.start();
        t2.start();
    }
}

在这个例子中,before方法在执行后调用notify()方法,这会唤醒一个在此对象监视器上等待的线程。after方法调用wait()后,当前线程会等待直到其他线程调用此对象的notify()方法或notifyAll()方法。

5. Java中的高级线程管理

Java提供了一些高级工具来帮助管理线程池、执行周期性任务等。其中,ExecutorServiceScheduledExecutorService是两个非常有用的工具。

5.1 使用ExecutorService管理线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; i++) {
            Runnable worker = new MyRunnable("" + i);
            executor.execute(worker);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }
}

在这个例子中,我们创建了一个固定大小为3的线程池,并提交了5个任务。这些任务将由线程池中的线程执行。shutdown()方法会启动线程池的关闭序列,这意味着不再接受新任务,但已提交的任务将继续执行直到完成。

5.2 使用ScheduledExecutorService执行周期性任务
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledTaskExample {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Runnable task = new MyRunnable("task");
        int initialDelay = 1;
        int period = 1;
        scheduler.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
    }
}

这个例子展示了如何使用ScheduledExecutorService来安排一个任务每隔一秒执行一次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

懒人w

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

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

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

打赏作者

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

抵扣说明:

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

余额充值