Cracking the coding interview--Q18.6
2014-04-06 09:25
357 查看
题目
原文:
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---
原文:
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---
相关文章推荐
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目5
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目8
- Cracking the coding interview--Q18.3
- Cracking the coding interview--Q1.1
- Cracking the coding interview--Q20.4
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q3.4
- 【Cracking the coding interview】Q1.6(旋转矩阵)
- Cracking the coding interview--Q20.13
- 《Cracking the Coding Interview》——第17章:普通题——题目9
- Cracking the coding interview--Q5.7
- 《Cracking the Coding Interview》——第18章:难题——题目9
- 判断一个二叉树是否是平衡二叉树 Cracking the coding interview 4.1
- Cracking the coding interview--Q20.12
- [Cracking the Coding Interview] Chapter 1 - Arrays and Strings
- Cracking the coding interview--Q8.7
- Cracking the coding interview--Q9.4
- Cracking the coding interview--问题与解答
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目7
- Cracking the Coding Interview Q1.8