One Java question every day [11] and one java question 11

Source: Internet
Author: User

One Java question every day [11] and one java question 11

Question

How does synchronized implement thread synchronization? Modify the MyRunnableThread class in every Java question [10] to solve the problem where all three threads get 10.

Answer

Method 1:

Use the synchronized keyword to wrap code blocks that require thread security to achieve thread synchronization. Syntax format:

Synchronized (expression) {// code to be Synchronized}

The MyRunnableThread class in a Java question [10] Every day is changed:

package me.huangzijian;public class MyRunnableThread implements Runnable {    private int num = 10;    private Object obj = new Object();    @Override    public void run() {        int count = num;        for (int i = 0; i < count; i++) {            synchronized (obj) {                System.out.println(Thread.currentThread().getName() + ":" + num);                num--;            }        }    }}

 

Method 2:

The synchronized keyword is used to modify the method, and the whole method is used for process thread synchronization. Syntax format:

Public synchronized void function () {// method code}

The MyRunnableThread class in a Java question [10] Every day is changed:

package me.huangzijian;public class MyRunnableThread implements Runnable {    private int num = 10;    private Object obj = new Object();    @Override    public synchronized void run() {        int count = num;        for (int i = 0; i < count; i++) {            System.out.println(Thread.currentThread().getName() + ":" + num);            num--;        }    }}

Divergent thinking

1. synchronized keyword modifier. If no expression exists, how does it obtain the synchronization lock?

Answer:

2. For method 1, if all objects passed to synchronized are new, can the synchronization effect be achieved?

A: No. Because different threads correspond to different synchronization locks and are not exclusive, thread synchronization will become invalid.

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.