本节书摘来异步社区《Java线程与并发编程实践》一书中的第2章,第2.5节,作者: 【美】Jeff Friesen,更多章节内容可以访问云栖社区“异步社区”公众号查看。
2.5 练习
下面的练习用来测试你对第2章内容的掌握程度。
1.指出与线程相关的三个问题。
2.判断对错:当程序计算的正确性取决于相对时间或者调度器所控制的多线程交叉时,你会遇到数据竞争问题。
3.给出同步的定义。
4.指出同步的两种属性。
5.同步是如何实现出来的?
6.判断对错:当一个已经获取锁的线程调用任意Thread的任意sleep()方法时不会释放锁。
7.如何指定一个同步方法?
8.如何指定一个同步块?
9.给出活跃性的定义。
10.指出三种活跃性挑战。
11.如何区分volatile和synchronized关键字?
12.判断对错:Java让你能够安全地访问一个final的属性而无需进行同步。
13.指出下面CheckingAccount类存在的线程问题:
public class CheckingAccount
{
private int balance;
public CheckingAccount(int initialBalance)
{
balance = initialBalance;
}
public boolean withdraw(int amount)
{
if (amount <= balance)
{
try
{
Thread.sleep((int) (Math.random() * 200));
}
catch (InterruptedException ie)
{
}
balance -= amount;
return true;
}
return false;
}
public static void main(String[] args)
{
final CheckingAccount ca = new CheckingAccount(100);
Runnable r = new Runnable()
{
@Override
public void run()
{
String name = Thread.currentThread().
getName();
for (int i = 0; i < 10; i++)
System.out.println (name + "
withdraws $10: " +
ca.withdraw(10));
}
};
Thread thdHusband = new Thread(r);
thdHusband.setName("Husband");
Thread thdWife = new Thread(r);
thdWife.setName("Wife");
thdHusband.start();
thdWife.start();
}
}```