具有两个线程的Java多线程同步方法 [英] Java multithreading synchronized method with two threads

查看:241
本文介绍了具有两个线程的Java多线程同步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的代码,但无法理解.

I have a very simple code but unable to understand.

    public class Test extends Thread {

        public synchronized void testPrint() {
            System.out.println("I am sleeping..."
                    + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
                System.out.println("I am done sleeping..."
                        + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            Test t = new Test();
            t.testPrint();

            System.out.println("I am out..." + Thread.currentThread().getName());
        }

        public static void main(String[] args) {
            Test t1 = new Test();
            Test t2 = new Test();

            t1.start();
            t2.start();

        }
    }

这是我的问题

我的成绩低于预期,

I am getting below result,

我在睡觉...线程-0

I am sleeping...Thread-0

我在睡觉...线程-1

I am sleeping...Thread-1

我睡完了...线程-0

I am done sleeping...Thread-0

我不在...线程-0

I am out...Thread-0

我睡完了...线程-1

I am done sleeping...Thread-1

我不在...线程1


从输出中,这绝对意味着创建了两个对象,这就是为什么两个线程都可以输入sync方法的原因.希望我的理解是正确的? 系统如何维护这两个对象?


From the output, It definitely means that there are two objects created, that is why both the threads could enter in the sync method. hope my understanding is correct ? How system maintains these two objects?

推荐答案

在运行Test t = new Test() jvm时,在堆上创建新对象,并将带有指向该对象的链接的变量t放入当前线程的堆栈中. 当您在两个或多个不同的线程中运行该代码时,它们每个都有自己的堆栈,因此它们每个都创建自己的变量t和对象Test

When you run Test t = new Test() jvm create new object on heap and put variable t with link to that object on stack of current thread.
When you run that code in two or more different threads each of them have own stack, so each of them create his own variable t and object Test

这篇关于具有两个线程的Java多线程同步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆