不同的线程可以在java中同时访问同一对象的不同独立方法吗?

时间:2017-11-06 15:37:37

标签: java multithreading

假设我们有两个线程,一个对象有两个方法。 线程1使用method1。 虽然线程1使用的method1仍在运行,但是线程2可以使用method2吗?

所有这一切都假设对象没有考虑多线程(没有同步或类似),并且方法不访问相同的变量。

此代码表明有可能:

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class multithreadaccess {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) throws IOException {
        TestClass tc = new TestClass();

        // invokes not sync method
        FirstThreadRunnable ftr = new FirstThreadRunnable(tc);
        Thread t1 = new Thread(ftr);

        // invokes the sync method
        SecondThreadRunnable str = new SecondThreadRunnable(tc);
        Thread t2 = new Thread(str);

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

        System.in.read();
    }


    public static class TestClass {

        private int callCount = 0;

        public void secondmethod() {
            System.out.println("second method activated! Call number:" + " [" + callCount++ + "] from thread: "
                    + Thread.currentThread().getId());
        }

        public void firstmethod() throws InterruptedException {
            // Test with the sleep
            System.out.println("starting first slow method from thread: " + Thread.currentThread().getId());
            Thread.sleep(1000); // hold the monitor for 5sec
            System.out.println("stopping first slow method! Call number:" + " [" + callCount++ + "] from thread: "
                    + Thread.currentThread().getId());

            // Test with spinning
            /*
             * System.out.println("MAKE IT SPIN! from thread: " +
             * Thread.currentThread().getId()); boolean spin = true;
             * while(spin){
             * 
             * } System.out.println("IT STOPPED SPINNING! from thread: " +
             * Thread.currentThread().getId()); }
             */
        }
    }

        // invokes the not sync method
        public static class FirstThreadRunnable implements Runnable {
            TestClass tester = null;

            public FirstThreadRunnable(TestClass tester) {
                this.tester = tester;
            }

            @Override
            public void run() {
                try {
                    tester.firstmethod();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }

        // invokes the sync method
        public static class SecondThreadRunnable implements Runnable {

            TestClass tester = null;

            public SecondThreadRunnable(TestClass tester) {
                this.tester = tester;
            }

            @Override
            public void run() {
                tester.secondmethod();
            }
        }
    }

来自here

的修改代码 但是,我不明白这是怎么回事。我一直在想一个对象是线性代码。但这表明线性只是方法中的代码(只要多个方法没有使用变量)?

1 个答案:

答案 0 :(得分:4)

您的代码问题是2种方法firstmethodsecondmethod不是"独立"如你所想,因为两者都有callCount++

这可能会创建race condition,因为两个线程都在更新该变量。您需要使用AtomicInteger而不是int,然后代码将起作用。

编辑: 通常,默认情况下不启用同步机制("自动阻止"),因为这些操作很昂贵并且会使程序变慢。这就是为什么Java提供synchronized关键字以及线程安全类(如AtomicInteger)以确保对共享变量和关键部分的正确访问。

相关问题