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

当我们给一个方法加了synchronized关键字,我们确保了两个线程不能同时执行同一个对象的该方法。所以对于第一问的答案是根据情况而定,如果两个线程有对象的同一个实例,那么答案是不行,它们不能同时执行方法A,但是当它们有对象的不同实例,那么它们就可以。我们可以用锁的概念来理解,一个synchronized方法就是在该实例对象上加了锁的方法,这样就阻止了其他线程执行该实例的其他synchronized方法。

对于第二部分,由于方法B并没有synchronized关键字,所以当线程2运行方法B时不会有东西阻碍线程1运行方法A,而且不论线程1和2是否有相同的实例对象。总而言之,需要牢记的是,只有一个同步synchronized方法可以在对象中的一个实例中执行,其他线程可以执行该实例的非同步non-synchronized方法,或者他们可以执行该对象的其他实例的任何方法。

public class Foo {
private String name; public Foo(String nm) {
name = nm;
} public String getName() {
return name;
} public void pause() {
try {
Thread.sleep(1000 * 3);
} catch(InterruptedException e) {
e.printStackTrace();
}
} public synchronized void methodA (String threadName) {
System.out.println("thread" + threadName + " starting; " + name + ".methodA()");
pause();
System.out.println("thread" + threadName + " ending: " + name + ".methodA()");
} public void methodB(String threadName) {
System.out.println("thread " + threadName + " starting: " + name + ".methodB()");
pause();
System.out.println("thread " + threadName + " ending: " + name + ".methodB()");
}
} public class MyThread extends Thread {
private Foo foo;
public String name;
public String firstMethod;
public MyThread(Foo f, String nm, String fM) {
foo = f;
name = nm;
firstMethod = fM;
} public void run() {
if (firstMethod.equals("A")) {
foo.methodA(name);
} else {
foo.methodB(name);
}
}
} public class j {
public static void main(String[] args) {
System.out.println("Part 1 Demo with same instance.");
Foo fooA = new Foo("ObjectOne");
MyThread thread1a = new MyThread(fooA, "Dog", "A");
MyThread thread2a = new MyThread(fooA, "Cat", "A");
thread1a.start();
thread2a.start();
while (thread1a.isAlive() || thread2a.isAlive()) {}
System.out.println("\n\n"); System.out.println("Part 1 Demo with different instance.");
Foo fooB1 = new Foo("ObjectOne");
Foo fooB2 = new Foo("ObejctTwo");
MyThread thread1b = new MyThread(fooB1, "Dog", "A");
MyThread thread2b = new MyThread(fooB1, "Cat", "A");
thread1b.start();
thread2b.start();
while (thread1b.isAlive() || thread2b.isAlive()) {};
System.out.println("\n\n"); System.out.println("Part 2 Demo.");
Foo fooC = new Foo("ObjectOne");
MyThread thread1c = new MyThread(fooC, "Dog", "A");
MyThread thread2c = new MyThread(fooC, "Cat", "B");
thread1c.start();
thread2c.start();
}
}

CareerCup All in One 题目汇总

[CareerCup] 16.6 Synchronized Method 同步方法的更多相关文章

  1. java synchronized静态同步方法与非静态同步方法,同步语句块

    摘自:http://topmanopensource.iteye.com/blog/1738178 进行多线程编程,同步控制是非常重要的,而同步控制就涉及到了锁. 对代码进行同步控制我们可以选择同步方 ...

  2. Java Synchronized Method This Static Class Object 区别

    1. 必须基于对象 Synchronized Method 和 Synchronized(this) 块,除了范围小点 (方法和块),没差别都是阻塞整个对象 - 如果对象有多个 Synchronize ...

  3. [CareerCup] 16.5 Semphore 信号旗

    16.5 Suppose we have the following code:public class Foo { public Foo() { . . . } public void first( ...

  4. Java并发编程实战(使用synchronized实现同步方法)

    本文介绍java最基本的同步方式,即使用synchronized关键字来控制一个方法的并发访问,如果一个对象已用synchronized关键字声明,那么只有一个执行线程允许去访问它,其它试图访问这个对 ...

  5. [CareerCup] 16.4 A Lock Without Deadlocks 无死锁的锁

    16.4 Design a class which provides a lock only if there are no possible deadlocks. 有很多方法可以避免死锁的发生,一个 ...

  6. [CareerCup] 16.3 Dining Philosophers 哲学家聚餐问题

    16.3 In the famous dining philosophers problem, a bunch of philosophers are sitting around a circula ...

  7. [CareerCup] 16.2 Measure Time in a Context Switch 测量上下文转换的时间

    16.2 How would you measure the time spent in a context switch? 上下文转换发生在两个进程之间,比如让一个等待进程进入执行和让一个运行进程进 ...

  8. [CareerCup] 16.1 Thread and Process 线程和进程

    16.1 What's the difference between a thread and a process? 进程Process是程序执行时的一个实例.一个进程是被分配系统资源的独立单元,每个 ...

  9. Java多线程初学者指南(11):使用Synchronized块同步方法

    synchronized关键字有两种用法.第一种就是在<使用Synchronized关键字同步类方法>一文中所介绍的直接用在方法的定义中.另外一种就是synchronized块.我们不仅可 ...

随机推荐

  1. WebBrowser控件打开https站点

    背景: 与上一篇博文一样,此文亦是由于开发DropboxAPI中遇到问题衍生出来的.由于需要重定向https类型网站,但自己的https证书是自签名的,总是提示'网站的安全证书存在问题'. 鉴此,查了 ...

  2. [UI]实用案例--Shape绘制实用圆圈

    Android允许通过xml定义资源,常见的事string,id,integer,dimen等,也可以定义一些图片资源,比如用来做几何的矢量图就非常好用,其中有许多的细节问题,具体需求可以再结合goo ...

  3. 智能车学习(十二)——智能车原理

    一.直立行走任务分解 1.任务分解 (1) 控制车模平衡:通过控制两个电机正反向运动保持车模直立平衡状态 (2) 控制车模速度:通过调节车模的倾角来实现车模速度控制,实际上最后还是演变成通过控制电机的 ...

  4. ASP.Net MVC开发基础学习笔记(5):区域、模板页与WebAPI初步

    一.区域—麻雀虽小,五脏俱全的迷你MVC项目 1.1 Area的兴起 为了方便大规模网站中的管理大量文件,在ASP.NET MVC 2.0版本中引入了一个新概念—区域(Area). 在项目上右击创建新 ...

  5. 在WebBrowser中通过模拟键盘鼠标操控网页中的文件上传控件(转)

    引言 这两天沉迷了Google SketchUp,刚刚玩够,一时兴起,研究了一下WebBrowser. 我在<WebBrowser控件使用技巧分享>一文中曾谈到过“我现在可以通过WebBr ...

  6. 实现Web验证码图片-原理

    实现验证码的基础 GDI+ graphics device interface plus的缩写,即图形设备接口.GDI+为开发者提供了一组实现与各种设备(具有图形化能力但不涉及图形细节的设备)进行交互 ...

  7. 《DSP using MATLAB》示例Example4.10

    上代码: b = [1, 0.4*sqrt(2)]; a = [1, -0.8*sqrt(2), 0.64]; % compute the polynomials coefficients given ...

  8. 判断密文加密类型hash-identifier

    判断密文加密类型hash-identifier   在安全领域中,加密数据随处可见.而在这些数据中,重要的数据往往采用哈希算法进行加密.例如,Linux密码使用sha512,Windows密码采用LM ...

  9. XAML数据绑定(Data Binding)

    XAML数据绑定(Data Binding)   Data Binding可以使得XAML标签属性的赋值更为灵活和方便.在绑定过程中,获取数据的标签成为目标标签:提供数据的标签成为源标签.在XAML中 ...

  10. 贪心 Codeforces Round #289 (Div. 2, ACM ICPC Rules) B. Painting Pebbles

    题目传送门 /* 题意:有 n 个piles,第 i 个 piles有 ai 个pebbles,用 k 种颜色去填充所有存在的pebbles, 使得任意两个piles,用颜色c填充的pebbles数量 ...