search
HomeJavajavaTutorialDetailed explanation of Java multi-threading interview questions

Question 1

A thread is executing a synchronized method in an object. Can thread B execute a non-synchronized method in the same object at the same time?

Yes, the two threads require different resources to run and do not need to preempt.

Case 1,

package duoxiancheng2;

/**
 * @author yeqv
 * @program A2
 * @Classname Ms1
 * @Date 2022/2/7 19:08
 * @Email w16638771062@163.com
 */
public class Ms1 {
    //A线程正在执行一个对象中的同步方法,B线程是否可以同时执行同一个对象中的非同步方法?
    Object a = new Object();

    public static void main(String[] args) {
        var t = new Ms1();
        new Thread(() -> t.a1()).start();//A线程
        new Thread(() -> t.a2()).start();//B线程
    }

    void a1() {
        synchronized (a) {
            System.out.println("同步方法");
        }
    }

    void a2() {
        System.out.println("非同步方法");
    }
}

Run result:

Detailed explanation of Java multi-threading interview questions

Question 2

Same as above, can thread B be executed at the same time? Another synchronized method in the same object?

No, two threads need a common resource to execute. The common resource is synchronized and can only be occupied by one thread at the same time.

Case 2,

package duoxiancheng2;

import java.util.concurrent.TimeUnit;

/**
 * @author yeqv
 * @program A2
 * @Classname Ms2
 * @Date 2022/2/7 19:25
 * @Email w16638771062@163.com
 */
public class Ms2 {
    //同上,B线程是否可以同时执行同一个对象中的另一个同步方法?
    Object a = new Object();
    public static void main(String[] args) {
        var t = new Ms2();
        new Thread(() -> t.a1()).start();//A线程
        new Thread(() -> t.a2()).start();//B线程
    }
    void a1() {
        synchronized (a) {
            System.out.println("进入同步方法1");
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("同步方法1结束");
        }
    }
    void a2() {
        synchronized (a) {
            System.out.println("进入同步方法2");
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("同步方法2结束");

        }
    }
}

Running result:

Thread A runs first and occupies resources.

Detailed explanation of Java multi-threading interview questions

After thread A finishes running and releases resources, thread B can enter execution

Detailed explanation of Java multi-threading interview questions

Thread B completes execution

Detailed explanation of Java multi-threading interview questions

Question 3

Will the lock be released if the thread throws an exception?

Yes, the resource will be released immediately after the thread throws an exception.

Case 3,

package duoxiancheng2;

import java.util.concurrent.TimeUnit;

/**
 * @author yeqv
 * @program A2
 * @Classname Ms3
 * @Date 2022/2/7 19:41
 * @Email w16638771062@163.com
 */
public class Ms3 {
    //线程抛出异常会释放锁吗?
    Object a = new Object();

    public static void main(String[] args) {
        var t = new Ms3();
        new Thread(() -> t.a1()).start();//A线程
        new Thread(() -> t.a2()).start();//B线程
    }

    void a1() {
        int c = 3;
        int b;
        synchronized (a) {
            System.out.println("进入同步方法1");
            try {
                b = c / 0;
                System.out.println(b);
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("同步方法1结束");
        }
    }

    void a2() {
        synchronized (a) {
            System.out.println("进入同步方法2");
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("同步方法2结束");

        }
    }
}

Result: As soon as an exception occurs in the method, the resources will be released immediately. Thread two starts executing

Detailed explanation of Java multi-threading interview questions

Question four

Write a program to prove that the AtomicInteger class is more efficient than synchronized

synchronized is more efficient

Case 1

package duoxiancheng2;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yeqv
 * @program A2
 * @Classname Ms4
 * @Date 2022/2/7 20:04
 * @Email w16638771062@163.com
 */
public class Ms4 {

    AtomicInteger n = new AtomicInteger(10000);
    int num = 10000;

    public static void main(String[] args) {

        var t = new Ms4();
        new Thread(t::minus, "T1").start();
        new Thread(t::minus, "T2").start();
        new Thread(t::minus, "T3").start();
        new Thread(t::minus, "T4").start();
        new Thread(t::minus, "T5").start();
        new Thread(t::minus, "T6").start();
        new Thread(t::minus, "T7").start();
        new Thread(t::minus, "T8").start();

    }

    void minus() {
        var a = System.currentTimeMillis();
        while (true) {
           /* if (n.get() > 0) {
                n.decrementAndGet();
                System.out.printf("%s 售出一张票,剩余%d张票。 %n", Thread.currentThread().getName(), n.get());
            } else {
                break;
            }*/
            synchronized (this) {
                if (num > 0) {
                    num--;
                    System.out.printf("%s 售出一张票,剩余%d张票。 %n", Thread.currentThread().getName(), num);
                } else {
                    break;
                }


            }


        }
        var b = System.currentTimeMillis();
        System.out.println(b - a);
    }
}

synchronized result:

Detailed explanation of Java multi-threading interview questions

AtomicInteger result:

Detailed explanation of Java multi-threading interview questions

Question 5

Write a program to prove that multiple methods of the AtomXXX class do not constitute atomicity

package demo16;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 写一个程序证明AtomXXX类的多个方法并不构成原子性
 */
public class T {
    AtomicInteger count = new AtomicInteger(0);

    void m() {
        for (int i = 0; i < 10000; i++) {
            if (count.get() < 100 && count.get() >= 0) { //如果未加锁,之间还会有其他线程插进来
                count.incrementAndGet();
            }
        }
    }

    public static void main(String[] args) {
        T t = new T();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(t::m, "thread" + i));
        }
        threads.forEach(Thread::start);
        threads.forEach((o) -> {
            try {
                //join()方法阻塞调用此方法的线程,直到线程t完成,此线程再继续。通常用于在main()主线程内,等待其它线程完成再结束main()主线程。
                o.join(); //相当于在main线程中同步o线程,o执行完了,main线程才有执行的机会
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println(t.count);
    }
}

Question 6

Write a program to start 100 threads in the main thread, 100 After the thread completes, the main thread prints "Done"

package cn.thread;

import java.util.concurrent.CountDownLatch;

/**
 * 写一个程序,在main线程中启动100个线程,100个线程完成后,主线程打印“完成”
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 16
 */
public class T12 {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                String tn = Thread.currentThread().getName();
                System.out.printf("%s : 开始执行...%n", tn);
                System.out.printf("%s : 执行完成,程序结束。%n", tn);
                latch.countDown();
            }, "T" + i).start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("---------------------------------------");
        System.out.println("100个线程执行完了。");
        String tn = Thread.currentThread().getName();
        System.out.printf("%s : 执行完成,程序结束。%n", tn);
    }
}

The above is the detailed content of Detailed explanation of Java multi-threading interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use