Java thread class with parameters parameterizedthread--that is, how to pass parameters to thread

Source: Internet
Author: User
Tags thread class

In Java, there seems to be no thread implementation class with running parameters, nor is it found in the third-party class library. I was surprised that there were a lot of articles on the Internet that discussed the issue, but did not provide a good code encapsulation solution. If the reader is aware of the official or third-party implementation, please note the message. At the end of this paper, a thread implementation class with running parameters is given.

The relevant solution has long been provided in the base Class library of C #, as follows: The method of creating a child thread with parameters provided by C # .

New Thread ((param) ={     Console.WriteLine (param);}); Th. Start (i); Task.Factory.StartNew ((param) ={     Console.WriteLine (param);}, I); ThreadPool.QueueUserWorkItem ((param) = {     Console.WriteLine (param);}, i);  

Let's start with an actual coding problem, where the main thread loops through a collection element and creates a sub-thread to do the appropriate processing (which can be time-consuming). Here's the initial implementation code, what's wrong with this code?

 for (int i = 0; i < i++) {Thread th = new Thread (new Runnable () {@Override public void run () {System.out.println (i + "");  } }); Th.start ();}          

  (1) First this program is not compiled, IntelliJ Tip "Variable ' i ' am accessed from within inner class,needs to be final or effectively final", prompting in Eclipse "Local Variable I Defined in an enclosing scope must is final or effectively final ", meaning that member variables in the outer class that are not final decorated are inaccessible in the inner class. Then it's easy for us to fix it in the following way:

for (int i = 0; i < i++) {    int p = i;    New Thread (newvoid run () {System.out.println (P + "");}}); Th.start ();}        

This code can be compiled and seems to work well. But it is not thread-safe, and the loop variable in the parent thread is constantly being modified, and the child thread gets the parent thread member variable that may be incorrect.

(2) Second, the above code in the loop to create a large number of sub-threads, the creation and destruction of threads will cause the overhead of system resources, it is generally recommended to use the thread pool to create threads, such as Threadpoolexecutor.

New linkedblockingqueue<runnable>());        For (int i = 0; i <; i++int p=i; Executor.execute ((),{System.out.println (P + "");}) ;}

So what is the way that the child thread can safely get to the parent thread of the variable, we can write the following thread implementation class:

Implements Runnable {    Object param;    Public this.param =void run () {System.out.println (param.tostring ());}}    

The problem here is that we have to write different sub-threading implementations for different situations, scatter a lot of similar scaffolding code in each project, and smell This "flavor", we should think of the need for code abstraction and encapsulation, so that it can be reused. Thus, the author uses Java to encapsulate a thread class with parameters:

/**@author@param*/interface parameterizedthreadstart<t>/**@paramvoid run (T context);       

/** * Parameterizedthread defines a thread with a generic parameter * @author wadexmy * @param <T>*/PublicClass parameterizedthread<t>Implements runnable{PrivateT context;Private parameterizedthreadstart<t>Parameterstart;/** * Constructor * @param context*/Public Parameterizedthread (T context,parameterizedthreadstart<t>Parameterstart) {this.context=context; this.parameterstart=Parameterstart;} /* * GetContext Returns the context of the current thread. * @return * /public  T getcontext () { return context;} /* * * Run method to is called in this separately executing thread. * /@Override public  void run () {Parameterstart.run (context);}}     

The class Parameterizedthread implements the Runnable, passing a parameter in the construction method and the method that needs to be executed. You can test this class with the following code:

New linkedblockingqueue<runnable>()); For (int i = 0; i < i++) {executor.execute (new Parameterizedthread<> (I, (p)) { Sys Tem.out.println (P.tostring ()); }));}

Java thread class with parameters parameterizedthread--that is, how to pass parameters to thread

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.