面试题
一、银行一个账户,同时有两个人分别向该账户存 3000 元,每次存 1000,存 3 次,每次存完打印用户余额
package com.test3; public class Test1 { public static void main(String[] args) { Account act = new Account(); Customer c1 = new Customer(act ); Customer c2 = new Customer(act ); c1.setName("账户1"); c2.setName("账户2"); c1.start(); c2.start(); } } class Account{ double balance; public Account() { } public synchronized void addMoney(double amt) { this.balance += amt; try { Thread.currentThread().sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+","+balance); } } class Customer extends Thread{ Account account; public Customer(Account act) { this.account = act; } @Override public void run() { for (int i = 0; i < 3; i++) { account.addMoney(1000); } } }
二、设计 4 个线程,其中两个线程每次对 j 增加 1 , 另外两个线程对 j 每次减少 1 写出程
package com.test3; public class Test3 { public static void main(String[] args) { NumberFactory num = new NumberFactory(); IncNumber incNumber = new IncNumber(num); DescNumber descNumber = new DescNumber(num); Thread inc1 = new Thread(incNumber); Thread inc2 = new Thread(incNumber); Thread inc3 = new Thread(descNumber); Thread inc4 = new Thread(descNumber); inc1.setName("线程一"); inc2.setName("线程二"); inc3.setName("线程三"); inc4.setName("线程四"); inc1.start(); inc2.start(); inc3.start(); inc4.start(); } } class NumberFactory{ int j; public NumberFactory() { } //自加 public synchronized void inc(int num) { j += num; System.out.println(Thread.currentThread().getName()+","+j); } //自减 public synchronized void desc(int num) { j -= num; System.out.println(Thread.currentThread().getName()+","+j); } } class IncNumber implements Runnable{ NumberFactory numberFactory; public IncNumber(NumberFactory num) { numberFactory = num; } @Override public void run() { numberFactory.inc(1); } } class DescNumber implements Runnable{ NumberFactory numberFactory; public DescNumber(NumberFactory num) { numberFactory = num; } @Override public void run() { numberFactory.desc(1); } }
三、使用两个线程打印 1 - 100。线程一和线程二交替打印
public class Test4 { public static void main(String[] args) { PrintNum p = new PrintNum(); Thread th1 = new Thread(p); Thread th2 = new Thread(p); th1.setName("线程一"); th2.setName("线程二"); th1.start(); th2.start(); } } class PrintNum implements Runnable{ int i = 1; @Override public void run() { while(true) { synchronized (this) { notify(); if (i <= 100) { System.out.println(Thread.currentThread().getName() + ":" + i); i++; } else { break; } try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }