Java programming notes 21 threads

Source: Internet
Author: User

1. Two methods to create a thread:

1) inherit the Thread class to implement the run method:

public class Hello1 extends Thread{String name;public Hello1(String n){name = n;}public void run(){for (int i=1; i<=10; i++){System.out.println(name+" Hello "+i);}}}

2) Implement the runnable interface to implement the run method:

public class Hello2 implements Runnable{String name;public Hello2(String n){name = n;}public void run(){for (int i=1; i<=10; i++)System.out.println(name+" Hello "+i);}}

The second method is recommended;

2. Generate thread object and startup thread

public class ThreadsExample1{public static void main(String argv[]){Hello1 h1 = new Hello1("Thread1");Hello2 h2 = new Hello2("Thread2");Thread t1 = new Thread(h1);Thread t2 = new Thread(h2);t1.start();t2.start();}}

3. Stop the thread.

The following run method can keep the thread running:

Public class hello3 implements runnable {string name; Public hello3 (string N) {name = N;} public void run () {int I = 0; while (true) // write the run method {I ++; system. out. println (name + "hello" + I );}}}

Add a loop condition to stop the off-the-shelf effect:

Public class hello4 implements runnable {string name; Boolean isstop; Public hello4 (string N) {name = N; isstop = false;} public void run () {int I = 0; while (! Isstop) {I ++; system. Out. println (name + "hello" + I) ;}} public void stop () // control condition {isstop = true ;}}

When a thread object enters the dead state, there is no way to return to other States.

4. Pause the thread.

Sleep method:

Yield Method

Join method,

Let's look at an example of join:

MotherThread:
Package ch22; public class motherthread implements runnable {public void run () {system. out. println ("Mom prepared for cooking"); system. out. println ("Mom found Rice Wine used up"); system. out. println ("mom asks her son to buy rice wine"); thread son = new thread (New sonthread (); son. start (); system. out. println ("mom is waiting for her son to buy rice wine"); try {son. join ();} catch (interruptedexception IE) {system. err. println ("an exception occurred! "); System. err. println ("Mom interrupted cooking"); system. exit (1);} system. out. println ("Mom starts cooking"); system. out. println ("Mom cooked ");}}

Sonthread:

Package ch22; public class sonthread implements runnable {public void run () {system. out. println ("son goes out to buy rice wine"); system. out. println ("it takes five minutes for the son to buy things"); try {for (INT I = 1; I <= 5; I ++) {thread. sleep (1, 1000); system. out. print (I + "min") ;}} catch (interruptedexception IE) {system. err. println ("Son accident");} system. out. println ("\ n son bought rice wine back ");}}

Cooking:
package ch22;public class Cooking{public static void main(String argv[]){Thread mother = new Thread(new MotherThread());mother.start();}}

Running result:

5. Data Synchronization

Now we have such a thread:

package ch22;public class ShareData implements Runnable{int i;public void run(){while (i<10){i++;for(int j=0; j<10000000; j++);System.out.println(Thread.currentThread().getName()+":"+i);}}}

Now we will generate two external data objects and run them for two threads:

package ch22;public class ThreadsExample2{public static void main(String argv[]){ShareData s1 = new ShareData();ShareData s2 = new ShareData();Thread t1 = new Thread(s1);Thread t2 = new Thread(s2);t1.start();t2.start();}}

Result

We can see that two thread objects are running interactively, and Thread 0 and thread 1 are respectively from 0 in order to 10.

This is because the two threads share the program code but do not share the data. Let's take a look at the effect of sharing the program code and data:

Package ch22; public class threadsexample3 {public static void main (string argv []) {encrypted data S = new encrypted data (); thread T1 = new thread (s ); // two small tables share one object; sharedatathread t2 = new thread (s); t1.start (); t2.start ();}}

The result is not from 0 to 10 as you think,:

Why ????

This is because the threads are separated and run. The specific analysis is omitted.

6. Synchronized achieves Thread Synchronization

Synchronized (the object to be locked)

{

Code to be locked

}

Package ch22; public class sync1_data implements runnable {int I; Public void run () {While (I <10) {/* The Lock Object is sync1_data, that is to say, the thread corresponding to this object needs to be synchronized */synchronized (this) {I ++; For (Int J = 0; j <10000000; j ++); system. out. println (thread. currentthread (). getname () + ":" + I );}}}}
Package ch22; public class threadsexample4 {public static void main (string argv []) {sync1_data S = new sync1_data ();/* t1 and t2 are the threads used to operate the same sync1_data object, * synchronization is required because sync1_data implements the lock mechanism */thread T1 = new thread (s); thread t2 = new thread (s); t1.start (); t2.start ();}}

Two threads synchronize operations on the same object

7. Wait for wait and notify

Examples of producers and consumers:

Package ch22; public class storage {private int count; // current inventory value private int size; // maximum inventory public storage (INT s) {size = s ;} // if the method in the class implements the lock, you must call this method to obtain the lock of the Class Object public synchronized void adddata (string N) {While (COUNT = size) // note why the while loop is used instead of if {try {This. wait (); // enters the waiting state} catch (interruptedexception e) {}} this. Y (); // notification that the consumer can consume count ++; system. out. println (n + "make Data Count:" + count);} public synchronized void deldata (string N) {While (COUNT = 0) {try {This. wait () ;}catch (interruptedexception e) {}} this. using Y (); system. out. println (n + "Use Data Count:" + count); count --;}}
package ch22;public class Producer extends Thread{private String name;private Storage s;public Producer(String n, Storage s){name = n;this.s = s;}public void run(){while (true){s.addData(name);try {sleep((int)Math.random()*3000);}catch (InterruptedException e) { } }}}
package ch22;public class Consumer extends Thread{private String name;private Storage s;public Consumer(String n, Storage s){name = n;this.s = s;}public void run(){while (true){s.delData(name);try {sleep((int)Math.random()*3000);}catch (InterruptedException e) { } }}}
package ch22;public class ThreadsExample5{public static void main(String argv[]){Storage s = new Storage(3);Producer p1 = new Producer("Producer1", s);Producer p2 = new Producer("Producer2", s);Consumer c1 = new Consumer("Consumer1", s);p1.start();p2.start();c1.start();}}

.........

Producer1 make Data Count: 3
Consumer1 Use Data Count: 3
Consumer1 Use Data Count: 2
Producer1 make Data Count: 2
Consumer1 Use Data Count: 2
Producer1 make Data Count: 2

.........

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.