第一题
单CPU的计算机中,CPU同时只能执行一条指令,因此,在仅有一个CPU的计算机上不可能同时执行多个任务。而操作系统为了能提高程序的运行效率,将CPU的执行时间分成多个时间片,分配给不同的线程,当一个时间片执行完毕后,该线程就可能让出CPU使用权限交付给下一个时间片的其他线程执行。当然有可能相邻的时间片分配给同一线程。之所以表面上看是多个线程同时执行,是因为不同线程之间切换的时间非常短,也许仅仅是几毫秒,对普通人来说是难以感知的,这样就看似多个线程在同时执行了。
第二题
线程实例调用start()方法和调用run()方法有着天壤之别,前者是调用实例方法,只有主线程执行,只有一条执行路径,后者是启动线程。
第三题
创建状态、就绪状态、运行状态、阻塞状态、终止状态
第四题
Thread:
public class Test {
public static void main(String[] args) {
Mythread thread1 = new Mythread();
thread1.start();
}
}
class Mythread extends Thread{
public void run(){
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
Runnable:
public class Test2 {
public static void main(String[] args) {
Thread thread1 = new Thread(new Mythread2());
thread1.start();
}
}
class Mythread2 implements Runnable{
public void run(){
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
第五题
public class Account {
private int balance=500;
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
balance=balance-amount;
}
}
public class TestAccount implements Runnable {
private Account acct = new Account();
public void run() {
for (int i = 0; i < 5; i++) {
makeWithdrawal(100); // 取款
if (acct.getBalance() < 0) {
System.out.println("账户透支了!");
}
}
}
private synchronized void makeWithdrawal(int amt) {
if (acct.getBalance() >= amt) {
System.out.println(Thread.currentThread().getName() + " 准备取款");
try {
Thread.sleep(500); // 0.5秒后实现取款
} catch (InterruptedException ex) {
}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName() + " 完成取款");
} else {
System.out.println("余额不足以支付" + Thread.currentThread().getName()
+ " 的取款,余额为 " + acct.getBalance());
}
}
}
public class TestWithdrawal {
public static void main(String[] args) {
TestAccount r=new TestAccount();
Thread one=new Thread(r);
Thread two=new Thread(r);
one.setName("张三");
two.setName("张三的妻子");
one.start();
two.start();
}
}