Java Thread notes (i)

Source: Internet
Author: User

Basic concepts of threads and processes

Processes and threads are dynamic concepts.

The process is "executing the program", is a verb, and the program is a noun, the process runs the "code" of the program, but also has its own counter, register, it will apply system resources to the system.

A thread is a control flow in a process. A program may contain multiple tasks running concurrently, while threads refer to the execution flow from one task to the end.

The simple point is that a thread is a task in execution, and a program contains multiple tasks.

Multithreading

In a single processor, in order to increase the processor utilization (the final target), so that the program in the IO input and so on do not need the processor, it can also allow the processor to operate, introduce multithreading mechanism. Multithreading can make the program run faster, more efficient execution, more interactive, it is self-evident!

Creating Tasks and Threads

A task is an object, so to create a task, you must define a class, define a task class, and to illustrate that this is a task class, it needs to implement the Runnable interface, which contains only one run method.

Once we have defined the task class Taskclass, we can create a task with its construction method: Taskclass task = new Taskclass (...) ;

The task we created can only be run in threads, and the thread class contains a number of ways to create a thread and control the thread. Create a task thread using the following statement: Thread thread = new thread (Task);

The start () method is then called to tell the Java virtual machine that the thread is ready to run: Thread.Start (), and then the Java Virtual machine executes the task by invoking the task's run () method.

Case code:

public class Taskthreaddemo{public static void Main (string[] args) {//Create a task and need to create a task class for the task, use the constructor method of the class to create the task Printchar PrintA = New Printchar (' A ', 100); Printchar PRINTB = new Printchar (' B ', 100); Printnum print100 = new Printnum (100);//create thread for task threads Thread1 = new Thread (PrintA); Thread thread2 = new Thread (PRINTB); Thread thread3= new Thread (print100),//tells the virtual machine thread to start running Thread1.start (); Thread2.start (); Thread3.start ();}} Class Printchar implements runnable{private char chartoprint;private int items;public Printchar (char c,int t) {Chartoprin t = C;items = t;} @Overridepublic void Run () {//TODO auto-generated method stubfor (int i=0;i<items;i++) {System.out.print (chartoprint );}}} Class Printnum implements Runnable{private int lastnumb;public printnum (int n) {lastnumb = n;} @Overridepublic void Run () {//TODO auto-generated method stubfor (int i= 1;i<100;i++) {System.out.print ("" +lastnumb); }}

}

A fun flashing text box, directly with the thread, without the Main method

Import Javax.swing.japplet;import Javax.swing.jlabel;public class Flashingtext extends JApplet implements Runnable { Private static final Long Serialversionuid = 1l;private JLabel jlbtext = new JLabel ("Welcome", Jlabel.center);p ublic Flashi Ngtext () {Add (Jlbtext); new Thread (This). Start (); public void Run () {try {while (true) {if (Jlbtext.gettext () ==null) jlbtext.settext ("Welcome"); else Jlbtext.settext (null ); Thread.Sleep (200);}} catch (Exception e) {//Todo:handle Exception}}}

Thread class

The thread class implements the Runnable interface, which contains construction methods for creating threads for tasks, and control methods, which are common thread-control methods of the thread class:

Because the thread class implements the Runnable interface, you can define a thread extension class that implements the Run method, which can also create a thread class, but it is not recommended because it mixes the mechanisms for creating tasks and running tasks together. It is better to detach the task from the thread, that is, to create the thread using the Runnable interface as much as possible, so that the resulting thread is more flexible and avoids the limitations of Java single inheritance.

Thread pool

The thread pool is the ideal way to manage the number of concurrent executions, and Java provides the executor interface to perform tasks in the thread pool, providing a Executorservice interface to manage and control tasks. To create a executor interface instance, we can use the executors class, which provides a static method for creating a executor interface object, describing the above-mentioned relationship above.

The shutdown () method in the thread pool is typically placed in the back part of the main method, and when all threads are added to the thread pool, it is possible to close the thread pools even if the threads are not executing, so the main method may end up than the Strand enters upgradeable.

Statistics on the run time of all threads in a thread pool using isterminated ()

If you want the main thread to execute after all the child threads are done, consider letting the child threads use the Jion method, but this may cause all child threads to become serial, not a good idea, and of course we can also multi-threading helper class Countdownlatch, which is a class with a bit similar functionality to timers. This time in reading study, found a better way is to add a shutdown () method after a while (!executor.isterminated ()) {}, this is a good way (but I put Shoudown () Method is placed behind the while statement, it is caught in a dead loop, and should be closed before the thread pool is judged to be all terminated, as it is also possible to add a new child thread after the while statement.

Isterminated () Method: Returns True if the thread is in the pool so the thread has completed and terminated.

You can use Countdownlatch and the methods above to run timing statistics on the program, but I remember that the Countdownlatch class is required to specify the number of threads.

Case code

import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class ExecutorDemo { public static void Main (string[] args) {Long start = System.currenttimemillis (); System.out.println ("Current Time" + "+start"); Executorservice executor = Executors.newfixedthreadpool (4); Executor.execute (New Printchar (' A ', 100));    Executor.execute (New Printchar (' B ', +)); Executor.execute (New Printchar (' C ', 100));        Executor.execute (New Printnum (100)); Executor.shutdown (); while (!executor.isterminated ()) {//system.out.print ("-");}; Long end = System.currenttimemillis (); System.out.println ("\ n Current Time" + "" +end); System.out.println ("\ n Time" + "" + (End-start) + "msec");}} 
Run
1 2

But do not know the reason for running too fast, or what other reasons, this method seems to be still not good, there will be 2 of the situation, the online very little about the isterminated () method of introduction, if the great God know why, also please tell the younger brother.

This blog is his own in the Java language programming in the advanced chapter of the note, the code from the book, the last time to add the timing part. Junior School is coming, I hope to learn Java is still in time.

This article is from the blog Garden Orchid Secluded, please indicate the source of the reprint.

Java Thread notes (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.