Thread concurrency review of traditional thread creation, timer and inter-thread Communication

Source: Internet
Author: User
Two traditional methods for creating threads
Write the Running code in the run method covered by the thread subclass and write the code in the run method of the runnable object passed to the thread object
 
Package CN. itcast. thread; public class traditionalthreadsynchronized {/*** @ Param ARGs */public static void main (string [] ARGs) {New traditionalthreadsynchronized (). init ();} public void Init () {final outputer = new outputer (); New thread (New runnable () {@ override public void run () {While (true) {try {thread. sleep (100);} catch (interruptedexception e) {e. printstacktrace ();} outputer. output ("zhangxiaoxiang ");}}}). start (); New thread (New runnable () {@ override public void run () {While (true) {try {thread. sleep (100);} catch (interruptedexception e) {e. printstacktrace ();} outputer. output ("lihuoming ");}}}). start ();} Private Static class outputer {// The Same monitor object must be used before the public void output (string name) {synchronized (outputer. this) {int Len = Name. length (); For (INT I = 0; I <Len; I ++) {system. out. print (name. charat (I);} system. out. println () ;}} public synchronized void output2 (string name) {int Len = Name. length (); For (INT I = 0; I <Len; I ++) {system. out. print (name. charat (I);} system. out. println ();} public static synchronized void output3 (string name) {int Len = Name. length (); For (INT I = 0; I <Len; I ++) {system. out. print (name. charat (I);} system. out. println ();}}}

 

new Thread(new Runnable(){public void run(){System.out.println("run method of runnable!");} }){public void run(){System.out.println("run method of thread!");}}.start();                 

Summary: Check the source code of the run () method of the thread class. We can see that both methods are actually calling the run method of the thread object. If the run method of the thread class is not overwritten, a runnable object is set for the thread object. The run method calls the run method of the runnable object. • A previous knowledge point involved: How to call non-default constructor of the parent class in the constructor of the anonymous internal class object. Practical Application: Second, why? The second method encapsulates the code into an object. Will the multi-threaded mechanism that is more in line with Java Object-Oriented Programming improve the program running efficiency? No. The running efficiency may be lower and the thread switching will consume resources. Why is there multi-thread download? Actually, the server bandwidth is occupied. the computer itself has not become faster, but has provided more services to the server. timer application: timer timertask can be implemented by quartz. quartz is an open-source job scheduling framework, which is fully written in Java and designed for j2se and J2EE applications. It provides great flexibility without sacrificing simplicity. You can use it to create simple or complex scheduling for executing a job. It has many features, such as database support, clusters, plug-ins, pre-Build of EJB jobs, javamail and others, and supports Cron-like expressions.

Do you need an application to execute a task? This task may only be executed on the last day of each month at every day or Tuesday. If a serious error occurs during the execution of an automatic task without intervention, can the application know that the task fails to be executed and try to execute it again? Are you and your team using Java programming? If any of these questions is answered, you should use the quartz scheduler.

Note: currently, Matrix Z is widely used in matrix. For example, the implementation of the ranking statistics function defines a scheduled job through quartz in jmatrix. Every morning, the job starts to work and recounts everyone's karma and ranking.

In addition, the generation of RSS files is also defined by quartz, which generates an rss xml file every 30 minutes.

Mutual Exclusion and communication between threads:

1. mutex: Use the synchronized (object) {} code block (ensure that the object is one) or add the synchronized keyword to the method.

Package CN. itcast. thread; public class traditionalthreadsynchronized {/*** @ Param ARGs */public static void main (string [] ARGs) {New traditionalthreadsynchronized (). init ();} public void Init () {final outputer = new outputer (); New thread (New runnable () {@ override public void run () {While (true) {try {thread. sleep (100);} catch (interruptedexception e) {e. printstacktrace ();} outputer. output ("zhangxiaoxiang ");}}}). start (); New thread (New runnable () {@ override public void run () {While (true) {try {thread. sleep (100);} catch (interruptedexception e) {e. printstacktrace ();} outputer. output ("lihuoming ");}}}). start ();} Private Static class outputer {// The Same monitor object must be used before the public void output (string name) {synchronized (outputer. this) {int Len = Name. length (); For (INT I = 0; I <Len; I ++) {system. out. print (name. charat (I);} system. out. println () ;}} public synchronized void output2 (string name) {int Len = Name. length (); For (INT I = 0; I <Len; I ++) {system. out. print (name. charat (I);} system. out. println ();} public static synchronized void output3 (string name) {int Len = Name. length (); For (INT I = 0; I <Len; I ++) {system. out. print (name. charat (I);} system. out. println ();}}}

 

2. Inter-thread Communication

 

Eg: The Sub-loop runs 10 times first, then the main loop runs 100 times, and then returns to the sub-loop 10 times. In this way, the sub-loop runs 50 times.

 

 
Public class threadtest {public static void main (string [] ARGs) {stubnew threadtest (). init ();} public void Init () {final business = new business (); New thread (New runnable () {publicvoid run () {for (INT I = 0; I <50; I ++) {business. subthread (I );}}}). start (); For (INT I = 0; I <50; I ++) {business. mainthread (I) ;}} private class business {booleanbshouldsub = true; // This defines a signal light public Sy that controls who executes Nchronized void mainthread (int I) {If (bshouldsub) Try {This. wait ();} catch (interruptedexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}for (Int J = 0; j <5; j ++) {system. out. println (thread. currentthread (). getname () + ": I =" + I + ", j =" + J);} bshouldsub = true; this. notify ();} public synchronizedvoid subthread (int I) {If (! Bshouldsub) Try {This. wait ();} catch (interruptedexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}for (Int J = 0; j <10; j ++) {system. out. println (thread. currentthread (). getname () + ": I =" + I + ", j =" + J);} bshouldsub = false; this. notify ();}}}

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.