java有几种实现线程的方式?

共有三种: (1 )继承Thread类,重写run函数创建: classxxextendsThread{publicvoidrun(){Thread.sleep(1 000) //线程休眠1 000毫秒。
sleep使线程进入Block状态,释放资源}} 启动线程:object.start() //启动线程,运行run函数 (2 )实现Runnable接口,重写run函数启动线程:Threadt=newThread(object) //创建线程对象 t.start()(3 )实现Callable接口,重写call函数。
Callable 是一个类似于 Runnable 的接口。
实现 Callable 接口的类和实现 Runnable 的类是可以由其他线程执行的任务。
 

Java多线程编程中,currentThread()方法究竟返回哪个线程对象?

Thread.currentThread() 方法始终返回调用该方法的当前线程的对象引用。
它不返回多个线程对象。
在多线程并发场景中,每个线程在调用时都会获得自己独立的线程对象。
具体描述如下: 核心机制 Thread.currentThread()是Java线程类(Thread)的静态方法。
它的作用是返回运行代码的线程对象。
This method behaves the same whether the program is in a single- or multi-threaded environment: it returns a reference to the thread that called it.例如,当线程A调用时,返回线程A对象,当线程B调用时,返回线程B对象。
两者互不干扰。
多线程场景下的性能在并发执行中,每个线程都有独立的执行栈和线程对象。
Suppose thread A and thread B are running concurrently: when thread A executes Thread.currentThread(), an instance of thread A is returned, including the ID, name, priority, and other attributes of thread A. When thread B executes the same method, an instance of thread B is returned.这种机制与CPU核心数、并发强度无关。
即使有数百个线程同时调用,每个线程仍然只能获取自己的引用。
与并发机制的关系 多线程的“并发”是指多个线程交替或同时使用CPU资源,但每个线程的上下文(包括局部变量、程序计数器等)是完全隔离的。
currentThread() 的返回值反映了这种隔离:它始终绑定到调用者的线程上下文,而不是共享全局对象。
For example, if two threads call currentThread().getName() at the same time, the names of their respective threads will be returned instead of the same value. Typical application scenarios: Thread self-management: The thread can obtain its own reference through this method, and then change properties (such as setting its name) or call other methods (such as interrupt() to interrupt itself). Debugging and Logging: Record current thread information (such as Thread.currentThread().getId()) in the log to distinguish the operations of different threads.资源分配:主线程可以通过比较currentThread()的返回值来判断当前是否运行在子线程中,从而动态调整其资源分配策略。
code example publicclassCurrentThreadDemo{publicstaticvoidmain(String[]args){ThreadmainThread=Thread.currentThread();System.out.println("Mainthread:"+mainThread.getName ());ThreadworkerThread=newThread(()->{Threadcurrent=Thread.currentThread();System.out.println("Workerthread:"+current.getName());});workerThread.start();}} Output result: Mainthread:mainWorkerthread:Thread-0 The respective main thread and subthread returns the current thread and subthread() differently, proving that they obtain independent references.要点摘要 简单返回值:对 currentThread() 的每次调用仅返回一个线程对象,即调用者本身。
Thread safety: The method itself is thread safe because it does not rely on shared state, and each thread gets access to its own private data when it is called. Design intent: Java provides self-awareness for each thread through this method, which is the basis for implementing thread cooperation (such as wait/notify mechanism) and avoiding race conditions.通过Thread.currentThread(),Java多线程编程可以精确定位并发环境中的线程身份,为复杂的并发控制提供基础支持。

Java多线程之ThreadPoolExecutor原理(图文代码实例详解)

ThreadPoolExecutor类似于Java的线程池变量。
多线程开发基本上都是基于此来进行特定业务的开发。
Although I feel that I have answered, there are many articles about this topic in online articles, but writing one by one alone will finally give you a deeper understanding than looking at others, so recently I have been systematically classifying the knowledge of Java.那么我们来探讨一下这个多线程框架的基础知识。
The ThreadPoolExecutor constructor is introduced as a member variable public ThreadPoolSize(intcorePoolSize, intmaximumPoolSize, longkeepAliveTime, TimeUnitunit, BlockingQueue workQueue 7 parameters in this constructor, the size of the core pool is the number of core threads. Even if the thread is idle, the thread pool always waits for the number of threads, unless the allowCoreThreadTimeOut parameter is set to a real maximum size. The maximum number of threads in the thread pool is the process live time and the workQueue is used to hold tasks. The threadFactory is a factory that creates a thread. When the number of threads is exceeded and the queue is full, the reject policy should be applied willAtomicIntegerctl=newAtomicInteger(ctlOf(RUNNING,0)); privatestaticfinalintCOUNT_BITS=integer.SIZE-3 ; privatestaticfinalintCAPACITY=(1 < First, let's look at a typical business code.将任务提交到线程池执行的函数是通过execute 或submit 方法。
区别在于提交期货和作废退货。
接下来我们主要分析一下实现过程。
提交线程涉及异步返回。
后面我们也,如果单独分析的话,下面这个函数就可以看到线程池的整个执行过程, publicvoidexecute(Runnablecommand){ if(command== null)thrownewNullPointerException(); erthancore 池大小读取正在进行中,尝试按照给定命令从第一个*任务*开始。
t,并通过*erweshouldhaveaddreadread*(因为通过检查杀死睡眠者)或*通过返回 false 在此方法中关闭池来防止误报。
ted *andsorejectthetask Offer(command)) {intrecheck=ctl.get(); When set to 0, thisWorkerCountOf(checkback) 为0,则非线程进程队列函数addWorker( null,false ); } else (!addWorker( order, false ))拒绝( order ); } The thread pool execution flow chart is as follows: I believe the whole process is clear to students: When the thread number is created, the worker number is the number of threads and the number of circuits executed. When the number of threads is W orker thread > corePoolSize, when the job is added to the task queue, corePoolSize < maxPoolsize>在实现过程中,有一些小细节在真正的源码中是不容易被忽视的。
The process of rechecking the thread state and the number of threads in the thread pool is the process of adding a new worker thread to the thread pool.向线程池添加新的worker任务的过程主要是addWorker方法。
Since the code is relatively long, I wrote the comment privatebooleanaddWorker(RunnablefirstTask,booleancore){ try again: for(;;){ intc=ctl.get();intrs=runStateOf(c);//Checkifqueueemptyonlyifnecessary.if(rs>=SHUTDOWN) so if the case is not in progress, shutdown, stop, aborted! This means that when the SHUTDOWN condition is removed and the first job is the task queue is empty and the task queue is not empty //, it will directly return false and the job thread will fail to add. returnfalse;for(;;){intwc=WorkerCountOf(c);if(wc>=CAPACITY||wc>=(Core?CorPoolSize:maximumPoolSize)) return false; if(compareAndIncrementWorkerCoun t(c))breakretry;c=ctl.get();//re-readctlif(runStateOf(c)!=rs)continueretry;//elseCASfailedduetoworkerCountchange;retryinnerloop}}booleanworkerStarted=false;booleanworkerAdded=false;Workerw= null;尝试{ w=newWorker(firstTask);finalThreadt=w.thread;if(t!=null){ FinalReentrantLockmainLock=this.mainLock;mainLock.lock(); null)){ //if the thread pool is in the shutdown state and the first job is empty(t.job is empty) )// precheckthattisstartablethrownewIllegalThreadStateException();//join the set of worker threads workers.add(w);ints=workers.size(); if(s>large pool size)//set the maximum number of stringslargestPoolSize=s;workerAd}=e finally {-mainLock.unlock();-}-if(workerAdded){-t.start();workerStarted=true;}}} finally{if The reason for adding this judgment is mainly because the thread pool is multi-threaded and can call lock and other methods to close the thread pool.因此,在每一步之前都必须再次检查线程池的状态。
除了运行状况之外,最重要的一点就是线程池It is only a closed condition, and the work queue is not empty, so the processing work of the work thread can be increased. Determine whether the number of threads in the thread pool is the number of core threads and then greater than the number of core threads. If the increased number of core threads is not the number of threads, then increase the number of threads by 1 to CAS, and then the reread ctl will match the state when the current state starts entering the loop. Create a worker object, the first parameter Runnable is the first executed task, then get the access lock of the main lock, and then judge the state of the thread pool closed again, and then add the worker object to the collection of the worker thread. If it evaluates to greater than the size of the large pool, assign the size of the job to the size of the large pool and set the worker to true and finally if true in the worker add then the worker initialization method is called to start the worker thread. If WorkerAdded fails, the currently added worker thread is removed from the Worker's Set and the number of threads in the thread pool is decremented by 1 . From the working code below, we can see that it implements the actionable interface. In the previous section, when the worker is started, the start method is called.真的是操作系统调度的吗?ecrementWorkerCount();returnnull;}//计算线程池中的线程数 intwc=workerCountOf(c);//Areworkerssubjecttoculling?//allowedCoreThreadTimeOut 参数设置为 true 或者线程池中的线程数大于 corePoolSize 所需工作时间。
timed=allowCoreThreadTimeOut||wc>corePoolSize;//线程数超过最大线程数||((wc>maximumPoolSize||(time&timedOut))//线程数大于1 或者任务队列为空则超时 void&&(wc>1 ||workQueue.isEmpty()))){ //CAS线程数减1 if(compareAndDecr ementWorkerCount(c))returnnull;继续; try{ //如果需要运行已经过期的worker,则直接获取任务等待时间或者池在任务中停留的时间。
如果不运行过期的worker // 直接调用它并阻塞,直到任务队列中有任务为止。
获取后,返回 Runnale 任务 Runnabler=timed?workQue ue.poll(keepAliveTime,TimeUnit.NANOSECONDS):workQueue.take();if(r!=null)returnr;timedOut=true;}catch(InterruptedExceptionretry){timedOut from 上述处理;如果任务执行过程中出现错误,则将线程池中的线程数减少1 2 个。
在线程池中添加主锁全局锁。
这里的主要区别在于,当worker执行任务时,它会获取worker中的锁。
完成任务后,添加1 ,并将该worker从worker集中删除。
3 、执行tryTerminate函数,查看线程池是否关闭。
4 、根据线程池状态是否添加非主工作线程运行pri。
vatevoidprocessWorkerExit(Workerw, boolean Completedabrupt){ //任务执行过程中出现异常,则(ifabrupt) //ifabrupt,则workerCountwan'tcrement decrementWorkerCount() ///如果找到线程池主键则将作业减1 rantLockmainLock=this.mainLock;//锁定mainLock.lock(); try{ //完成任务并1 completedTaskCount+=w.completedTasks;//从worker收集器中移除workerworkers.remove(w)finally { mainLock. Open the pool.尝试关闭池) ctlintc=ctl.get();//如果线程池的状态值小于STOP,则即使SHUTDOWNRUNNINGif(runStateLessThan(c,STOP)){ //执行过程中没有异常(!if Complete意外){ //如果不需要allowCoreThreadTimeOut参数,如果这不为true,则线程。
// 对于常驻有corePoolSize线程的线程池 intmin=allowCoreThreadTimeOut?0:corePoolSize;if(min==0&&!workQueue.isEmpty())min=1 ;//如果线程池数量大于最小值,无需增加,线程就会执行任务if(workerCountOf(c)\u003 e\u003 e min) return;//不需要替换}//这里走表示线程池中线程数为0,如果任务队列不为空,则需要添加一个线程来做工作 addWorker( null, false ); } } t