线程同步相关的问题

时间:2014-03-23 13:24:29

标签: java multithreading synchronization

我最近开始在java中学习多线程。我正在尝试同步的各种场景。这是我的代码

 package main_classes;
public class Synchronized_test implements Runnable {
    public Object lock2=new Object();
    private static int shared_var;
    public Synchronized_test()
    {
        shared_var=0;
    }

    int getsharedvarvalue()
    {
        return shared_var;
    }

    void setsharedvarvalue(int i)
    {
        shared_var=i;
    }

    public void run() 
    {
        synchronized(lock2)
        {
            System.out.println("Child Thread: Waiting");
            for(int i=0;i<5;i++)
            {
                //this.setsharedvarvalue(i);
                System.out.println("Child Thread: Shared Variable = " + shared_var);
            }
        }
    }

    //@SuppressWarnings("unused")
    public static void main(String args[]) throws InterruptedException
    {
        Synchronized_test st=new Synchronized_test();
        Thread t=new Thread(new Synchronized_test());
        t.start();
        synchronized(st.lock2)
        {
            for(int i=0;i<5;i++)
            {
                st.setsharedvarvalue(i);
                System.out.println("Main Thread: Shared Variable = " +st.getsharedvarvalue());
            }

        }
    }
}

这是输出

Child Thread: Waiting
Main Thread: Shared Variable = 0
Child Thread: Shared Variable = 0
Main Thread: Shared Variable = 1
Child Thread: Shared Variable = 1
Main Thread: Shared Variable = 2
Child Thread: Shared Variable = 2
Main Thread: Shared Variable = 3
Child Thread: Shared Variable = 3
Main Thread: Shared Variable = 4
Child Thread: Shared Variable = 4

根据我在线阅读的理解,如果某个其他线程获取了锁,则线程必须等待。因此,根据代码,首先获取锁定的线程将打印出所有值,然后第二个线程应该执行。但是从输出看来,两个线程都在同步块内并同时运行。请解释一下这种行为。

PS:此输出不是我得到的唯一输出。有时我得到的输出与上面提到的理论一致。喜欢这个

Child Thread: Waiting
Child Thread: Shared Variable = 0
Child Thread: Shared Variable = 0
Child Thread: Shared Variable = 0
Child Thread: Shared Variable = 0
Child Thread: Shared Variable = 0
Main Thread: Shared Variable = 0
Main Thread: Shared Variable = 1
Main Thread: Shared Variable = 2
Main Thread: Shared Variable = 3
Main Thread: Shared Variable = 4

2 个答案:

答案 0 :(得分:2)

你只运行一个线程对象,不是吗?

  Synchronized_test st=new Synchronized_test();
    Thread t=new Thread(new Synchronized_test());
    t.start();

仅启动帖子t,而您根本没有运行st

答案 1 :(得分:0)

您只运行一个主题&#39;。请注意,st是Synchronized_class的一个实例,它实现了Runnable接口。你必须开始一个新的线程&#39; t0&#39;。请尝试以下代码:

Thread t0 = new Thread(new Synchronized_test());
Thread t = new Thread(new Synchronized_test());
t0.start();
t.start();

此外,您的代码不清楚,无法理解“同步语句”的概念。我建议您从链接http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html尝试一个简单的同步语句示例。它可以清除您的理解并帮助您更好地构建代码。