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. leetcode4568

    date: 2015-09-13 16:32:49 Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of ...

  2. 使用canvas实现擦玻璃效果---转载

    <!DOCTYPE html> <html> <head lang="zh"> <meta name="viewport&quo ...

  3. SQL详解(下)

    约束 *约束是添加在列上的,用来约束列的! 1. 主键约束(唯一标识)  特点:非空,唯一,被引用  创建表时指定主键的两种方式,分别为:    CREATE TABLE stu(     sid   ...

  4. Java数组课后作业

    1.运行TestArrays.java,了解Arrays中的一些重要方法的用法. Arrays.equals(a 1, a2):判断数组是否相等. int[] b = Arrays.copyOf(a, ...

  5. Golang 安装及配置教程 for Mac

    1.到golang.org下载golang 并安装. 2.安装sublimetext ,打开之后 按ctrl+` 打开命令行,输入以下内容: import urllib2,os; pf='Packag ...

  6. HTML元素的offsetWidht、clientWidth、scrollWidth属性区别

    每个HTML元素都有以下属性 offsetWidth:内容+内边距(padding)+边框+滚动条宽度,以css像素返回它的屏幕尺寸. offsetHeight:(同上) offsetLeft:如果o ...

  7. EF框架step by step(5)—处理实体简单属性

    EF框架会对实体进行跟踪,对实体的每个属性当前值和原始值及其状态进行跟踪,记录.当前值是指实体属性当前的被赋予的值,而原始值是指实体最初从数据库读取或者附加到DbContext时的值. 先通过简单的代 ...

  8. iOS学习21之UILabel, UITextField, UIButton, UIImageView

    1.UILabel 1> 概述 UILabel (标签): 是显示文本的控件.在App中 UILabel 是出现频率最高的控件 UILabel 是 UIView 子类,作为子类一般是为了扩充父类 ...

  9. soapui中文操作手册(八)----Web服务的功能测试案例

    现在,让我们来看看在一个TestCase的功能测试. 展开 Simple TestSuite并双击Simple Login and Logout w. Properties Steps. 正如你所看到 ...

  10. [转]crontab命令指南

    原文链接:http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html 前一天学习了 at 命令是针对仅运行一次的任务,循环运行的例行性计划 ...