Java Multithreading (i)

Source: Internet
Author: User

Do you have any idea what a thread is when you learn or use threads?

This is explained in most books and articles: threads are a single sequential control flow in a program. A relatively independent, scheduled execution unit within a process is the unit of dispatch for the system to dispatch and dispatch CPUs independently of the operating program.

Is there a second question: How do you create a thread?

Let's continue classics: 1. Use the subclass of the thread class to create a thread 2. Create a thread with the Runnable interface

Now my understanding tells me that a class inherits thread or implements runnable even if it is a thread. But in fact this kind of understanding will pit itself.

For example, when I think about the thread pool problem, I fall out of the hole, since whether it is inherited thread or implementation runnable are threads, and the thread is independent, then why can the pool thread continue to use it? (question three)

I began to understand the problem and began to read and search for information.

I got a little bit of a http://blog.csdn.net/hsuxu/article/details/8985931 when I saw this article on the thread pool principle.

Then continue to see the thread and Runnable source code and understand the point.

 public  class   Thread implements runnable{ //  paste only the local code  /*   What'll be Run.   */ private   Runnable target; @Override  public  void   run () { if  (target! = null  ) {Target.run (); }    }}

Note that thread implements the Runnable, andthread writes the Target.run () that is used in the run ();

Now let's write another 2 ways to implement threading

 Public classThreadTest1extendsthread{@Override Public voidrun () { for(inti = 0;i<10;i++) {System.out.println (i); Try{sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }         Public Static voidMain (string[] args) {NewThreadTest1 (). Start (); }}

 Public classRunnableTest1Implementsrunnable{@Override Public voidrun () { for(inti = 0;i<10;i++) {System.out.println (i); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }         Public Static voidMain (string[] args) {thread thread=NewThread (NewRunnableTest1 ());    Thread.Start (); }}

The class that inherits the thread is using new ThreadTest1 (). Start ();

The class that implements the runnable is thread thread = new Thread (new RunnableTest1 ()); Thread.Start ();

That is, to start a thread you call the start () method of the thread class (or his subclass) !

So what did start () do after that?

Start () waits for the CPU resource and then runs run ().

High-energy warning here

The class that inherits the thread is actually starting a new thread at startup, and implementing the Runnable class (I feel that the class that implements the runnable should say that the task analogy that defines the thread execution is called the threading class more appropriate) is initiated by placing his instance in a thread instance.

That is, set the thread in the

Private Runnable Target;

That is to say, the thread can put Runnable An instance of a can also put Runnable B. It's almost like I can think of a thread that can perform a different task!

But you can actually modify the private Runnable target in the thread at run time; It? The answer is not clear to me ...

However, the above linked article gives an implementation of the method

By defining a worker thread to implement, see the following code specifically

Private classWorkthreadextendsThread {//whether the worker thread is valid to end the worker thread        Private BooleanIsRunning =true; /** The key is that if the task queue is not empty, then the task execution is removed, and if the task queue is empty, wait*/@Override Public voidrun () {Runnable R=NULL;  while(isrunning) {//Note that if the thread is invalid, the Run method ends naturally, and the thread is useless.                synchronized(taskqueue) { while(IsRunning && taskqueue.isempty ()) {//queue is empty                        Try{taskqueue.wait (20); } Catch(interruptedexception e) {e.printstacktrace (); }                      }                      if(!Taskqueue.isempty ()) R= Taskqueue.remove (0);//Remove Task                }                  if(r! =NULL) {r.run ();//Perform Tasks} finished_task++; R=NULL; }          }            //stop working and let the thread run through the Run method naturally ends         Public voidStopworker () {isrunning=false; }      }

He has covered the run () method, where it passes through the while loop and sets Runnable r = null; The value of R to implement a thread to perform a different task. Here I have a question: Can I use an interface without Runnable ? For example, I define a task interface

 Public Interface Task {    publicabstractvoid  dotask ();}

Then modify the Workthread class above to

Private classWorkthreadextendsThread {//whether the worker thread is valid to end the worker thread        Private BooleanIsRunning =true; /** The key is that if the task queue is not empty, then the task execution is removed, and if the task queue is empty, wait*/@Override Public voidrun () { Task t =NULL;  while(isrunning) {//Note that if the thread is invalid, the Run method ends naturally, and the thread is useless.                synchronized(taskqueue) { while(IsRunning && taskqueue.isempty ()) {//queue is empty                        Try{taskqueue.wait (20); } Catch(interruptedexception e) {e.printstacktrace (); }                      }                      if(!Taskqueue.isempty ()) T = Taskqueue.remove (0);//Remove Task                }                  if(T!=NULL) { T. Dotask ();//Perform Tasks} finished_task++; T =NULL; }          }            //stop working and let the thread run through the Run method naturally ends         Public voidStopworker () {isrunning=false; }      }

Doesn't that look the same? I feel no problem for the time being ... I feel that the reason Runnable is different from the others is because thread inherits Runnableand then implements the run () method, which is called by the Run method when the thread is started, which makes it seem Runnable. The modified workthread in the overwrite the run () method modifies the actual task, then I think it is OK to define an interface to define the running task.

These are the little thoughts about the thread pool today.

Java Multithreading (i)

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.