DAY11 (multi-threaded, wake-up mechanism, production consumer mode, multi-threaded life cycle)

Source: Internet
Author: User

A: Process:

Process refers to a program that is running. To be exact, when a program goes into memory, it becomes a process, and the process is a program that is in the process of running and has a certain independent function.

B: Thread:

A thread is an execution unit in a process that is responsible for the execution of a program in the current process, with at least one thread in a process. There can be multiple threads in a process, and this application can also be called a multithreaded program.

C: In short:

After a program runs at least one process, a process can contain multiple threads

Thread implementation

Two ways to implement

Inherit thread

public class MyThread extends thread{@Overridepublic void Run () {for (int i = 0; i <; i++) {System.out.println (getn Ame () + ":" +i);}}}

Test class

public class MyThread02 extends thread {@Overridepublic void run () {MyThread t=new MyThread ();//Create an object directly to create a thread        T.start ();}}    

  

Implement Runnable

public class Mythreadimp implements Runnable{int num;public mythreadimp (int num) {this.num=num;} @Overridepublic void Run () {for (int i = 0; i < 5; i++) {System.out.println (Thread.CurrentThread (). GetName () +num++);}}

Test class

public class Test01 {public static void main (string[] args) {mythreadimp mt=new mythreadimp (10); Thread T=new thread (MT); T.setname ("Zhang San"); T.start (); Thread T1=new thread (MT); T1.setname ("John Doe"); T1.start ();}}

  

Multithreading Security Issues

Thread Security = = Security of data

① whether there are multiple threads

② If you have shared data

③ If there are more than one statement to perform shared data

Workaround Synchronized Sync Lock

eg

public class MyThread implements Runnable {int tickets;public MyThread (int tickets) {this.tickets = tickets;} Object o = new Object (), @Overridepublic Void Run () {while (true) {synchronized (O) {if (Tickets > 1) {System.out.printl N (Thread.CurrentThread (). GetName () + "-" + tickets--);}}}}

Test class

        MyThread mt=new MyThread (100); Thread T=new thread (MT); T.setname ("Window 1"); Thread T2=new thread (MT); T2.setname ("Window 2"); Thread T3=new thread (MT); T3.setname ("Window 3"); T.start (); T2.start (); T3.start ();            

If you do not give the line Cheng will produce data chaos, may produce-1; we cannot predict the result.

In the method of locking, the other method is to give the method lock eg:

public class MYTHREAD01 implements runnable{static int tickets=100;public MyThread01 (int tickets) {this.tickets = Tickets ;} @Overridepublic void Run () {while (true) {method01 ()}} Private synchronized void method01 () {if (Tickets >= 1) {System.out.println (Thread.CurrentThread (). GetName () + "-" + ti ckets--);}}}

  

The case of stealing red envelopes:

public class MyThread implements Runnable {int. Money;int count;public MyThread (int money, int count) {This.money = Money;t His.count = Count;} @Overridepublic void Run () {//generates a random number method ();} Private synchronized void method () {if (Count > 1 && Money! = 0) {Random r = new Random ();d ouble d = (r.nextint (money) + 1); money-= D; System.out.println (Thread.CurrentThread (). GetName () + ":" + D); count--;} else {System.out.println (Thread.CurrentThread (). GetName () + ":" + Money);}}}

Test class

public class Hongbao {public static void main (string[] args) {MyThread mt=new MyThread (10,3); Thread T=new thread (MT); T.setname ("Zhang San"); T.start (); t.setpriority (10); Thread T1=new thread (MT); T1.setname ("John Doe"); T1.start (); Thread T2=new thread (MT); T2.setname ("Li"); T2.start ();}}

  

Production Consumer Model:

Explains the multi-threaded wake-up mechanism (notify () is the method in object)

Using case columns in multi-threading

Product because just do test use not write full

public class Student {String  name;int Age;boolean flag;}

  

Producers wait if consumers do not have consumer products and only consume producers to produce them.

public class Stthread implements Runnable {private Student s;public stthread (Student s) {THIS.S = s;} int x; @Overridepublic void Run () {while (true) {synchronized (s) {if (S.flag) {///if flag=true; it means that there are already objects  that have not yet been consumed, Then wait for try {s.wait ();} catch (Interruptedexception e) {e.printstacktrace ();} Wait for}if (x% 2! = 0) {s.name = "Zhao Yun"; s.age =;} else {s.name = "Zhang Fei"; s.age = 22;} x++;s.flag=true;//Modify Tag s.notify ();//Wake}}}}

  

Consumers will wait for something to consume if they have nothing to consume.

public class Gtthread implements Runnable {private Student s;public gtthread (Student s) {THIS.S = s;} @Overridepublic void Run () {while (true) {//guaranteed to wait in synchronized (s) {if (!s.flag) {//flag=false) waits for the  student object to produce a try { S.wait ();//Thread Wait} catch (Interruptedexception e) {e.printstacktrace ();}} System.out.println (S.name + ":" + s.age); s.flag=false;s.notify ();}}}

  

Test class

public class Test {public static void main (string[] args) {Student s=new Student (); Stthread st=new Stthread (s); Gtthread gt=new Gtthread (s); Thread T1=new Thread (ST); Thread t2=new thread (GT); T1.start (); T2.start ();}}

Output results

Output: Zhao Yun: 44 Zhang Fei: 22 Zhao Yun: 44 Zhang Fei: 22 Zhao Yun: 44 Zhang Fei: 22 Zhao Yun: 44 ... the cycle continues

  

The life cycle of a thread

DAY11 (multi-threaded, wake-up mechanism, production consumer mode, multi-threaded life cycle)

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.