Multithreading in Java (learning notes)

Source: Internet
Author: User

A software college student is determined to become a programmer. He has just been familiar with java this semester. I hope the experts can give me some advice and I am very grateful.

I learned Java multithreading today. The following are my notes for your reference and review.

(1) This class must be extended from the Thread class to make itself a subclass of it.

(2) thread processing must be written in the run () method.

Note: The Thread class is stored in the java. lang class library, so you do not need to manually load the class and call start () to start the Thread.

3. Implement the Runnable interface to create a thread

Because Java cannot inherit multiple types of data, Java provides the Runnable interface to solve this problem. Declare the run () method in the interface. You can create a thread as long as the run () method is defined in the class.

The following is an example:

Public ClassMyRunnableImplementsRunnable {

Public VoidRun (){

System.Out. Println (Thread.CurrentThread(). GetName ());

// Obtain the current thread object

Then, call the getName () method of this thread.

 

}

 

/**

*@ ParamArgs

*/

Public Static VoidMain (String [] args ){

//TODOAuto-generated method stub

MyRunnable t1 =NewMyRunnable ();

MyRunnable t2 =NewMyRunnable ();

Thread th1 =NewThread (t1, "MyThread1 ");

Thread 2nd =NewThread (t2, "MyThread2 ");

Th1.start ();

Th2.start ();

}

}

4. Thread Management

Every thread will be in one of four States before it is created and dead: newly created, runnable, and blocked) and dead (dead );

When an object is created using new Thread (), the Thread is in this State, but the system does not configure resources until the Thread is started using the start () method;

When start () starts the thread, the thread enters the runable state, who first grabs the cpu and who starts to execute the run () method, other threads will wait in the queue for the opportunity to win cpu resources;

When the thread calls the wait () method of the object or the thread itself calls sleep (), the frozen state thread is generated. Sleep (long millis) can be used to set the sleep time, millis Millisecond (1/1000 seconds ). If this thread is joined with another thread (), other threads or program code that are not started will not be executed until the thread ends;

When a thread is frozen, it stops running () until the frozen factor disappears, and the thread returns to the runable state;

The reason for the freezing factor to disappear can be:

A. If the thread is frozen by the wait () of the called object, the notify () of the modified object can be lifted when it is called. (Notify y );

B. The thread enters the sleep state, but the specified time has reached.

When the thread's run () Execution ends or stop () is called, the thread enters the dead state.

Example:

1. if you want to simply design the sorting of threads, you can use join (). When a thread calls join, other threads will not start execution until the thread ends. In the following example, after the dog thread is completed, execute the cat thread. After the thread execution is completed, print "Hello world ";

// CTest. javapublic class CTest extends Thread {private String id; public CTest (String str) {id = str;} public void run () {for (int I = 0; I <4; I ++) {try {sleep (int) (1000 * Math. random ();} catch (InterruptedException e) {} System. out. println (id + "is running .. ") ;}}// App2.javapublic class App2 {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubCTest dog = new CTest ("doggy"); CTest cat = new CTest ("cat"); dog. start (); // start the dog thread try {dog. join (); // The cat can be executed only after the dog thread ends. start (); // start the cat thread cat. join (); // restrict execution of catch (InterruptedException e) {} System after the cat thread ends. out. println ("Hello World ");}}

Have you noticed the code try... catch? This is because sleep () and join () must be written in try... catch to catch possible exceptions.

Let's talk about synchronous processing. Let's take an example: Assume that a bank accepts the customer's remittance, and each remittance can calculate the total amount of the remittance, now there are two other customers, each of whom is divided into three times. Each time 100 yuan is imported, the total amount of bank remittances should be 600 yuan.

To solve this problem, let's write the code segment:

// CBank. javapublic class CBank {private static int sum = 0; public static void add (int n) {int tmp = sum; tmp = tmp + n; try {Thread. sleep (int) (1000 * Math. random ();} catch (InterruptedException e) {} sum = tmp; System. out. println ("sum =" + sum) ;}// CCustomer. javapublic class CCustomer extends Thread {// customer class, inherited from Thread class public void run () {for (int I = 1; I <= 3; I ++) CBank. add (1, 100 ); // import 100 yuan in three times} // App3.javapublic class App3 {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubCCustomer c1 = new CCustomer (); CCustomer c2 = new CCustomer (); c1.start (); c2.start ();}}


// Running result
Sums = 100
Sums = 200
Sums = 100
Sums = 300
Sums = 200
Sums = 300

The running result is different from the expected 600. This is because two threads share the same variable, and one of the threads has started before the run () ends, resulting in a computing error.

To get 600, you only need to let the first thread blow up and then process the second thread. This requires synchronization processing, that is, synchronized. add this keyword before add, it can coordinate the time of each thread and allow only one thread to enter run () for processing at a time. The Code is as follows:

// CBank. javapublic class CBank {private static int sum = 0; public synchronized static void add (int n) {int tmp = sum; tmp = tmp + n; try {Thread. sleep (int) (1000 * Math. random ();} catch (InterruptedException e) {} sum = tmp; System. out. println ("sum =" + sum) ;}// CCustomer. javapublic class CCustomer extends Thread {// customer class, inherited from Thread class public void run () {for (int I = 1; I <= 3; I ++) CBank. add (1, 100 ); // import 100 yuan in three times} // App3.javapublic class App3 {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubCCustomer c1 = new CCustomer (); CCustomer c2 = new CCustomer (); c1.start (); c2.start ();}}
Running result:
Sums = 100
Sums = 200
Sums = 300
Sums = 400
Sums = 500
Sums = 600

At this point, multi-thread learning is now here ..

 

 

 

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.