use*_*316 5 java multithreading synchronized
我写了一个程序,其中两个线程正在运行,这就是我使用synchronized关键字的原因.我的代码如下 -
public class TestThreadAnother {
public synchronized void decrement(){
try {
for (int i = 4; i > 0; i--) {
System.out.println("Thread " + i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestThreadClass extends Thread {
private String threadName;
TestThreadAnother obj1;
public TestThreadClass(String threadName, TestThreadAnother Obj1) {
this.threadName = threadName;
obj1 = Obj1;
System.out.println("Creating " + threadName);
}
@Override
public void run() {
System.out.println("Running " + threadName);
obj1.decrement();
System.out.println("End of " + threadName);
}
}
public class TestThreadMain {
public static void main(String[] args) {
TestThreadAnother obj1 = new TestThreadAnother();
TestThreadClass t1 = new TestThreadClass("Thread 1", obj1);
TestThreadClass t2 = new TestThreadClass("Thread 2", obj1);
t1.start();
t2.start();
}
}
Run Code Online (Sandbox Code Playgroud)
输出应该是 -
Creating Thread 1
Creating Thread 2
Running Thread 1
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 1
Running Thread 2
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 2
Run Code Online (Sandbox Code Playgroud)
但我得到以下结果 -
Creating Thread 1
Creating Thread 2
Running Thread 2
Thread 4
Thread 3
Running Thread 1
Thread 2
Thread 1
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 1
End of Thread 2
Run Code Online (Sandbox Code Playgroud)
但我的问题是,因为我使用同步方法然后为什么会发生这种情况?因为知道我是否使用synchronized,所以在第一个线程将执行然后第二个将执行.但在我的情况下,有时这不会发生.Java专家需要您的帮助来解决这个问题.
JB *_*zet 11
输出是正确的.只有你的decrement()方法是同步的.这意味着decrement()一次不能通过多个线程调用此对象的方法.但这并不妨碍其他线程在执行一个线程时执行其他操作decrement().
您的输出显示,虽然线程2正在执行decrement(),线程1是执行第一System.out.println()中run()方法中,然后可能等待线程2已经完成了其到呼叫decrement(),然后执行decrement().
你必须要了解的重要事情是.Synchronization只保证两个线程不会同时锁定同一个对象.在您的情况下,一个线程(thread2或thread1)将获得锁定并将调用decrement()方法.直到此线程结束,其他threda将被阻止.
现在,分析你的输出:
Creating Thread 1
Creating Thread 2
Running Thread 2 // Thread -2 has the lock now.
Thread 4 // thrad-2's decrement()
Thread 3
Running Thread 1 // thread-1 is blocked. So, only this line is printed
Thread 2 // still thread2
Thread 1 // still thread2
Thread 4 // now thread1 decrement() starts
Thread 3
Thread 2
Thread 1
End of Thread 1
End of Thread 2
Run Code Online (Sandbox Code Playgroud)
打印thread.getName()你的减量方法,以获得更好的主意.