一、前言线程算是相对较高级的内容,主要的原因不是说他难,而是它不可见。最近基于多线程的方式优化了一些 FLink 程序,所以这一系列,我们聊聊多线程
二 线程2.1 进程和线程关系图片.png进程是计算机系统进行资源分配和调度的最小单位,换句话说我们平时双击那些后缀为 .exe的文件时都会产生一个进程。
进程可以产生若干个线程,是程序执行的最小单位,换句话说,进程就是房子,线程就是房子内一个个干活的人
2.2 为什么需要线程线程在计算机编程中扮演着重要角色,其重要性主要体现在以下几个方面:
提高程序响应性:通过多线程处理,程序可以变得更加灵活和响应更加及时。在一个单线程程序中,如果有一个耗时的操作,会导致整个程序阻塞,影响用户体验;而多线程可以使程序保持活跃,允许其他线程继续执行,从而提高程序的响应性。提高程序性能:多线程可以充分利用多核处理器的优势,实现并发执行多个任务,加快程序运行速度,提高系统整体性能。通过并行执行,程序可以更有效地利用计算资源,加快任务完成的速度。实现并发处理:多线程允许程序同时执行多个任务,这对于需要同时处理多个事件或任务的应用程序至关重要。例如,在服务器端应用中,多线程可以同时处理多个客户端请求。资源共享:多个线程可以共享进程的资源,如内存空间、文件句柄等,这种资源共享有助于简化程序设计,并提高效率。不同线程之间可以相互通信、共享数据,协同工作来完成复杂任务。实现复杂逻辑:有些程序需要同时进行多项任务,通过多线程可以更好地组织和管理复杂的逻辑,提高程序的可维护性和可拓展性。实现异步编程:多线程可以实现异步操作和事件驱动,允许程序在等待某些操作完成时继续执行其他操作,提高程序的效率和灵活性。异步编程模型通过非阻塞方式进行任务处理,可以有效提升程序的吞吐量和性能。 综合以上原因,线程在计算机编程中是不可或缺的,它提供了一种有效的机制来实现并发处理、提高程序的响应性和性能、实现资源共享以及管理复杂的程序逻辑。因此,了解和灵活运用线程是提升程序效率和优化系统性能的重要手段。2.3 线程的状态代码语言:javascript代码运行次数:0运行复制public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
*
- {@link Object#wait() Object.wait} with no timeout
- {@link #join() Thread.join} with no timeout
- {@link LockSupport#park() LockSupport.park}
*
*
*
*
*
*
A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called Object.wait()
* on an object is waiting for another thread to call
* Object.notify() or Object.notifyAll() on
* that object. A thread that has called Thread.join()
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
*
- {@link #sleep Thread.sleep}
- {@link Object#wait(long) Object.wait} with timeout
- {@link #join(long) Thread.join} with timeout
- {@link LockSupport#parkNanos LockSupport.parkNanos}
- {@link LockSupport#parkUntil LockSupport.parkUntil}
*
*
*
*
*
*
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}2.4 如何创建线程代码语言:javascript代码运行次数:0运行复制Thread thread = new Thread();
thread.start();在Java中,当调用线程对象的start()方法时,实际上是调用了start0()方法,该方法会启动一个新的本地操作系统线程,
然后调用Java中的run()方法来执行线程的任务。所有 线程的主要工作的方法就是 run 方法,那么怎么样来丰富 run 方法的内容呢?
首先通过匿名内部类来启动线程,如:
代码语言:javascript代码运行次数:0运行复制Thread thread1 = new Thread(){
@Override
public void run() {
while (true){
if (Thread.currentThread().isInterrupted()){
System.out.println("Interruted!");
break;
}
Thread.yield();
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1==");
}
}
} ;
thread1.start();当然也可以实现 Runnable 接口来实现线程的功能
代码语言:javascript代码运行次数:0运行复制public class CreateThread3 implements Runnable {
public static void main(String[] args) {
Thread t1 = new Thread(new CreateThread3());
t1.start();
}
@Override
public void run() {
System.out.println("Oh,I am Runnable");
}
}2.5 线程停止2.5.1 使用标识代码语言:javascript代码运行次数:0运行复制public class ControlledThread extends Thread {
private volatile boolean shouldStop = false;
public void stopThread() {
shouldStop = true;
}
@Override
public void run() {
while (!shouldStop) {
// 线程执行的任务
System.out.println("Thread is running...");
}
System.out.println("Thread stopped.");
}
public static void main(String[] args) {
ControlledThread thread = new ControlledThread();
thread.start();
// 模拟停止线程
try {
Thread.sleep(3000); // 等待3秒
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stopThread();
}
}需要注意的是,这里使用 volatile 变量来保证该变量对于任意线程可见,如果不用 volatile 的话,则线程可能会无法停止
2.5.2 使用 interrup()代码语言:javascript代码运行次数:0运行复制public class InterruptedThread extends Thread {
@Override
public void run() {
while (!Thread.interrupted()) {
// 线程执行的任务
System.out.println("Thread is running...");
}
System.out.println("Thread stopped.");
}
public static void main(String[] args) {
InterruptedThread thread = new InterruptedThread();
thread.start();
// 模拟停止线程
try {
Thread.sleep(3000); // 等待3秒
thread.interrupt(); // 中断线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}三、总结文章围绕多线程的核心概念和应用展开,通过具体Java代码示例,深入讲解了线程的创建、状态管理以及线程停止的方法。作者强调了线程在优化程序性能和响应性方面的重要性,鼓励读者深入了解并灵活运用多线程编程技术