Java multithreading (synchronization and deadlock, producer and consumer issues)

Source: Internet
Author: User

Java multithreading (synchronization and deadlock, producer and consumer issues)

First, let's look at the synchronization and deadlock issues:


A deadlock means that A owns banana and B owns apple.

A said to B: If you give me apple, I will give you banana.

B said to a: If you give me banana, I will give you apple.


However, both A and B are waiting for the reply from the other party, so the final result is that A cannot get apple, and B cannot get banana. Such an endless loop is a deadlock.

So we can simulate the above description and write the following code:


Class A represents,

public class A {public void say(){System.out.println("A said to B: if you give me the apple, I will give you the banana.");}public void get(){System.out.println("A get the apple.");}}

Class B represents B,

public class B {public void say(){System.out.println("B said to A: if you give me the banana, I will give you the apple.");}public void get(){System.out.println("B get the banana.");}}

ThreadDeadLock indicates a deadlock,

public class ThreadDeadLock implements Runnable{private static A a=new A();private static B b=new B();public boolean flag=false;public void run(){if(flag){synchronized(a){a.say();try{Thread.sleep(500);}catch(InterruptedException e){e.printStackTrace();}synchronized(b){a.get();}}}else{synchronized(b){b.say();try{Thread.sleep(500);}catch(InterruptedException e){e.printStackTrace();}synchronized(a){b.get();}}}}}

The following is the main class:

public class Main{public static void main(String[] args){ThreadDeadLock t1=new ThreadDeadLock();ThreadDeadLock t2=new ThreadDeadLock();t1.flag=true;t2.flag=false;Thread thA=new Thread(t1);Thread thB=new Thread(t2);thA.start();thB.start();}}


Program running result:

A said to B: if you give me the apple, I will give you the banana.
B said to A: if you give me the banana, I will give you the apple.


From the above program running, we can find that both threads are waiting for the execution of the other side to complete, so that the program cannot continue to run, resulting in a deadlock.


Let's take a look at the producer and consumer issues:


The so-called producer and consumer problems are very simple. The process is that the producer continuously produces the product, and the consumer keeps taking the product.

Producer produces the product and Consumer consumes the product.

Therefore, we first define the product class:

public class Product {private String name="product";private boolean flag=false;public String getName() {return name;}public void setName(String name) {this.name = name;}public synchronized void set(String name){if(!flag){try{super.wait();}catch(InterruptedException e){e.printStackTrace();}}this.setName(name);try{Thread.sleep(300);}catch(InterruptedException e){e.printStackTrace();}flag=false;super.notify();}public synchronized void get(){if(flag){try{super.wait();}catch(InterruptedException e){e.printStackTrace();}}try{Thread.sleep(300);}catch(InterruptedException e){e.printStackTrace();}System.out.println(this.getName());flag=true;super.notify();}}

Here we add the wait and wake-up parameters, and add a flag. If the flag is true, it indicates production is available, but it cannot be removed. If the thread is executed to the consumer thread, it should wait, if the flag is false, it can be removed, but cannot be produced. If the producer thread runs, it should wait.


Producer class:

public class Producer implements Runnable{private Product product=null;public Producer(Product product){this.product=product;}public void run(){for(int i=0;i<50;++i){this.product.set("product");}}}

Consumer class:

public class Consumer implements Runnable{private Product product=null;public Consumer(Product product){this.product=product;}public void run(){for(int i=0;i<50;++i){try{Thread.sleep(100);}catch(InterruptedException e){e.printStackTrace();}this.product.get();}}}

Then the main class:

public class Main{public static void main(String[] args){Product product=new Product();Producer pro=new Producer(product);Consumer con=new Consumer(product);new Thread(pro).start();new Thread(con).start();}}

So we know that every time a producer produces a product, the consumer will take a product, and every time the consumer takes a product, it will wait for the producer to produce.

Related Article

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.