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---
- Cracking the coding interview--Q18.6
- Cracking the coding interview--Q18.1
- Cracking the coding interview--Q18.2
- Cracking the coding interview--Q18.3
- Cracking the coding interview--Q18.4
- Cracking the coding interview--Q18.5
- Cracking the Coding Interview
- 《Cracking the coding interview》
- Cracking The Coding Interview
- Cracking the coding interview
- Cracking the coding interview
- Cracking the coding interview--Q9.6
- Cracking the coding interview--Q1.6
- Cracking the coding interview--Q1.6
- Cracking the coding interview--Q3.6
- Cracking the coding interview--Q4.6
- Cracking the coding interview--Q5.6
- Cracking the coding interview--Q8.6
- 二叉树的操作
- jQuery学习第三课(选择器第二讲)
- 设置打开myeclipse时弹出select a workspace
- ./configure,make,make install
- 计算机基础_01
- Cracking the coding interview--Q18.6
- 统计一个子字符串在另一个字符串中出现的次数
- Android Bundle类
- [hdu 2010] 水仙花数
- 迷茫的人啊
- 南通滨海园区官方微信公众平台正式上线
- iOS开发中WebView的使用
- linux下php添加pdo_mysql扩展
- 设计模式学习笔记--设计模式在Java I/O中的应用(装饰模式和适配器模式)