代码如下:
(代码图片,没有想到这个排版是这个样子)
class BankAccount {
private int balance = 100;
public int getBalance() {
    return balance;
}
public void withdraw(int amount) {
    balance = balance - amount;
}
}
public class RyanAndMonicaJob implements Runnable {
private BankAccount account = new BankAccount();
public static void main (String[] args) {
    RyanAndMonicaJob theJob = new RyanAndMonicaJob();
    Thread one = new Thread(theJob);
    Thread two = new Thread(theJob);
    one.setName("Ryan");
    two.setName("Monica");
    one.start();
    two.start();
}
public void run() {
    for (int x = 0; x < 10; x++) {
        makeWithdrawal(10);
        if(account.getBalance() < 0) {
            System.out.println("Overdrawn!");
        }
    }
}
private void makeWithdrawal(int amount) {
    String currentThread = Thread.currentThread().getName();
    if(account.getBalance() >= amount) {
        System.out.println(currentThread + "is about to withdraw");
        try{
            System.out.println(currentThread + " is going to sleep");
            Thread.sleep(500);
        } catch(InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println(currentThread + " woke up.");
        account.withdraw(amount);
        System.out.println(currentThread + " completes the withdrawl");
    } else {
        System.out.println("Sorry, not enough for " + currentThread);
    }
}
}
上述代码是为了探究线程并发性的问题,但是输出如下图:
主要不理解的就是输出中前两句是第一个对象的线程在执行,然后就行sleep,那么这个时候就应该是另一个线程执行,那么这个第二个执行的为什么不是从头开始执行,而是从makeWithdrawl方法中间的部分开始执行。

额。。你自己试下其实就知道了。。和你想的不是一回事,两个线程同时在跑,同时在输入,中间的sleep导致了你有这样的错觉,你按我给你截的图圈起来的部分看。。。
还是搞不懂第二行和第三行的输出,可能是我对线程理解错了?
我可以理解为这两个对象在做同一个任务,一个sleep的时候那另一个就可以接着做这个任务。
如果这两个所做的任务不一样的话就是不会出现图中输出的第二行和第三行的东西。
@痴心—: 不是接着做的,你看代码是循环10次,这个截图只是后面的一部分,不是从头开始的。
两个线程是同时在跑的,只不过运行速度很快,。。截个开始的图给你看下吧。。书里的截图误导你了

@WMG-Eight: 我悟了,谢谢
好排版666
你可以看一下里面的两张图片