Cracking the coding interview--Q18.6

来源:互联网 发布:网络智能办公系统 编辑:程序博客网 时间:2024/06/01 18:25

题目

原文:

You are given a class with synchronized method A, and a normal method C. If you have two threads in one instance of a program, can they call A at the same time? Can they call A and C at the same time?

译文:

提供你一个含有同步方法A和普通方法C的类,如果你在程序的实例化中有两个线程,他们可以被A同时调用吗?他们能同时调用方法A和C吗?

解答

java提供两种方法实现同步:同步方法,同步代码块。

同步方法:类需要同步的方法用“synchronized”关键字修饰,如果一个线程正在执行一个同步方法,所有其他在同一个类的线程中含有需要被执行的同步方法的线程将堵塞。

如下:method1和method2需要被同步

public class SynchronizedMethod {

 // Variables declaration
public synchronized returntype Method1() {
// Statements
}
public synchronized returntype method2() {
// Statements
}
// Other methods

}

同步代码块:对需要同步的部分代码添加同步,而不是对整个方法同步,它需要提供一个实例化的Object作为锁。

例如:同步代码块中,this作为锁

synchronized(this) {
/* statement 1
* ...
* statement N */
}

所以,同一段实例化的程序中是不能同时调用具有同步功能的方法A的;但可以同时调用方法A和C。


---EOF---

0 0
原创粉丝点击