第七章

    xiaoxiao2022-07-03  121

    1>(1)A (2) B (3)C (4)C (5)A (6)C 4>

    public class word4_1 { public static void main(String[] args) { Mythread t = new Mythread(); t.start(); } } class Mythread extends Thread{ public void run(){ for(int i=1;i<=5;i++){ System.out.println(Thread.currentThread().getName()+":"+i); } } } public class word4_2 { public static void main(String[] args) { Thread t = new Thread(new Mythread2()); t.start(); } } class Mythread2 implements Runnable{ public void run(){ for(int i=1;i<=5;i++){ System.out.println(Thread.currentThread().getName()+":"+i); } } }

    5>

    public class word5_1 { public static void main(String[] args) { word5_2 word=new word5_2(); Thread one=new Thread(word); Thread two=new Thread(word); one.setName("张三"); two.setName("张三的妻子"); one.start(); two.start(); } } public class word5_2 implements Runnable{ private word5_3 word = new word5_3(); @Override public void run() { for (int i = 0; i < 5; i++) { makeWithdrawal(100); if (word.getbalance() < 0) { System.out.println("账户透支了!"); } } } private synchronized void makeWithdrawal(int num) { if(word.getbalance()>num){ System.out.println(Thread.currentThread().getName() + " 准备取款"); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } }else{ System.out.println("余额不足以支付"+Thread.currentThread().getName()+"的余额为"+word.getbalance()); } } } public class word5_3 { private int balance = 1000; public int getbalance() { return balance; } public void Calculation(int num){ balance = balance-num; } }
    最新回复(0)