炫意html5
最早CSS3和HTML5移动技术网站之一

java线程问题(Head FIrstJava中的例子)

代码如下:
(代码图片,没有想到这个排版是这个样子)

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导致了你有这样的错觉,你按我给你截的图圈起来的部分看。。。

炫意HTML5 » java线程问题(Head FIrstJava中的例子)

Java基础教程Android基础教程