final java2 excercise 2013

Upload: vinh-nguyen-huu

Post on 01-Mar-2016

39 views

Category:

Documents


0 download

DESCRIPTION

Java

TRANSCRIPT

Lp trnh hng i tng vi Java 2

Hng Dn Thc HnhLp Trnh Java 2Khi: i Hc v Cao ngNm 2013

Hng dn: Bi tp thc hnh c chia theo Module Mi Module c thit k cho thi lng l 6 tit thc hnh ti lp vi s hng dn ca ging vin. Ty theo s tit phn b, mi tun hc c th thc hin nhiu Module. Sinh vin phi lm tt c cc bi tp trong cc Module tun tng ng. Nhng sinh vin cha han tt phn bi tp ti lp c trch nhim t lm tip tc nh. Cc bi c du (*) l cc bi tp nng cao dnh cho sinh vin kh gii.

Mc lcModule 1 : n tp Graphic User Interface.3Module 2: Thc hnh v MultiThreading.23Module 3: Thc hnh v Collections.34Module 4: Thc hnh v Networking.46Module 5: Thc hnh v JDBC.64Module 6: Thc hnh v JSP.75

MODULE 1Mc ch:n tp Graphic User Interface, gip cc sinh vin hiu c LayoutManager, Common Control, Event, DialogBox, Advanced Control. Sinh vin phi thc hin tt Module 1 ng dng cho cc Module tip theo, c bit l phn kt ni c s d liu.

Bi tp 1: Thc hnh cch hin th ca s Windows trong Java

Hy hin th ca s trn, yu cu vit class k tha t JFrameHng dn:

Gii thch:

Bi tp 2: Thc hnh v FlowLayoutFlowLayout cho php add cc control trn cng mt dng, khi no ht ch cha n s t ng xung dng, ta cng c th iu chnh hng xut hin ca control. Mc nh khi mt JPanel c khi to th bn thn lp cha ny s c kiu Layout l FlowLayout.

Hng dn:

Bi tp 3: Thc hnh v BoxLayoutBoxLayout cho php add cc control theo dng hoc ct, ti mi v tr add n ch chp nhn 1 control, do mun xut hin nhiu control ti mt v tr th bn nn add v tr l 1 JPanel ri sau add cc control khc vo JPanel ny.

BoxLayout.X_AXIS : Cho php add cc control theo hng t tri qua phi.BoxLayout.Y_AXIS : Cho php add cc control theo hng t trn xung di. BoxLayout s khng t ng xung dng khi ht ch cha, tc l cc control s b che khut nu nh thiu khng gian cha n.Hng dn:

Bi tp 4: Thc hnh v BorderLayoutBorderLayout gip chng ta hin th cc control theo 5 vng: North, South, West, East, Center

Nu nh khng c 4 vng : North, West, South, East. Th vng Center s trn y ca s, thng thng khi a cc control JTable, JTree, ListView, JScrollpane ta thng a vo vng Center n c th t co gin theo kch thc ca s gip giao din p hn.

Bi tp 5: Thc hnh v cc control cn bn JButton JLabel JTextField JTextArea ButtonGroup & JRadioButton JCheckBox JComboBox JListThit k giao din gii phng trnh bc 2:

Hng dn: Sinh vin phi xc nh Layout Manager trc, ta cng c th k hp cc Layout thit k giao din, t tn control theo yu cu bn di

Tn ControlTn Bin ControlM t

JTextFieldtxtSoaDng nhp gi tr cho a

JTextFieldtxtSobDng nhp gi tr cho b

JTextFieldtxtSocDng nhp gi tr cho c

JTextFieldtxtKetquaDng hin th kt qu

JButtonbtnGiaiVit lnh gii phng trnh

JButtonbtnXoaTrangXa ton b d liu trong dl

JButtonbtnThoatVit lnh thot chng trnh

JLabellblTieuDeGii Phng Trnh Bc 2

Bi tp 6: thit k giao din thc hin cc php ton : + - * :Thit k giao din nh hnh bn di:

Khi bm nt Gii th ty thuc vo php ton c chn m kt qu thc hin khc nhau.

import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class CongTruNhanChiaUI extends JFrame {private static final long serialVersionUID = 1L;public CongTruNhanChiaUI(String title){setTitle(title);}public void doShow(){setSize(400, 300);setLocationRelativeTo(null);setDefaultCloseOperation(EXIT_ON_CLOSE);addControl();setResizable(false);setVisible(true);}public void addControl(){JPanel pnBorder=new JPanel();pnBorder.setLayout(new BorderLayout());JPanel pnNorth=new JPanel();JLabel lblTitle=new JLabel("Cng Tr Nhn Chia");pnNorth.add(lblTitle);pnBorder.add(pnNorth,BorderLayout.NORTH);lblTitle.setForeground(Color.BLUE);Font ft=new Font("arial", Font.BOLD, 25);lblTitle.setFont(ft);JPanel pnWest=new JPanel();pnWest.setLayout(new BoxLayout(pnWest, BoxLayout.Y_AXIS));JButton btnGiai=new JButton("Gii ");JButton btnXoa=new JButton("Xa ");JButton btnThoat=new JButton("Thot");pnWest.add(btnGiai);pnWest.add(Box.createVerticalStrut(10));pnWest.add(btnXoa);pnWest.add(Box.createVerticalStrut(10));pnWest.add(btnThoat);pnBorder.add(pnWest,BorderLayout.WEST);pnWest.setBackground(Color.LIGHT_GRAY);Border southborder=BorderFactory.createLineBorder(Color.RED);TitledBorder southTitleBorder=new TitledBorder(southborder, "Chn tc v");pnWest.setBorder(southTitleBorder);JPanel pnSouth=new JPanel();pnSouth.setPreferredSize(new Dimension(0, 30));pnSouth.setBackground(Color.PINK);JPanel pns1=new JPanel();pns1.setBackground(Color.BLUE);pnSouth.add(pns1);JPanel pns2=new JPanel();pns2.setBackground(Color.RED);pnSouth.add(pns2);JPanel pns3=new JPanel();pns3.setBackground(Color.YELLOW);pnSouth.add(pns3);pnBorder.add(pnSouth,BorderLayout.SOUTH);JPanel pnCenter=new JPanel();pnCenter.setLayout(new BoxLayout(pnCenter, BoxLayout.Y_AXIS));pnBorder.add(pnCenter,BorderLayout.CENTER);Border centerborder=BorderFactory.createLineBorder(Color.RED);TitledBorder centerTitleBorder=new TitledBorder(centerborder, "nhp 2 s a v b:");pnCenter.setBorder(centerTitleBorder);

JPanel pna=new JPanel();JLabel lbla=new JLabel("nhp a:");final JTextField txta=new JTextField(15);pna.add(lbla);pna.add(txta);pnCenter.add(pna);JPanel pnb=new JPanel();JLabel lblb=new JLabel("nhp b:");final JTextField txtb=new JTextField(15);pnb.add(lblb);pnb.add(txtb);pnCenter.add(pnb);JPanel pnc=new JPanel();JPanel pnpheptoan=new JPanel();pnpheptoan.setLayout(new GridLayout(2, 2));pnpheptoan.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.BLACK),"Chn php ton:"));final JRadioButton radCong=new JRadioButton("Cng");pnpheptoan.add(radCong);final JRadioButton radTru=new JRadioButton("Tr");pnpheptoan.add(radTru);final JRadioButton radNhan=new JRadioButton("Nhn");pnpheptoan.add(radNhan);final JRadioButton radChia=new JRadioButton("Chia");pnpheptoan.add(radChia);ButtonGroup group=new ButtonGroup();group.add(radCong);group.add(radTru);group.add(radNhan);group.add(radChia);pnc.add(pnpheptoan);pnCenter.add(pnc);JPanel pnkq=new JPanel();JLabel lblkq=new JLabel("Kt qu:");final JTextField txtkq=new JTextField(15);pnkq.add(lblkq);pnkq.add(txtkq);pnCenter.add(pnkq);lbla.setPreferredSize(lblkq.getPreferredSize());lblb.setPreferredSize(lblkq.getPreferredSize());btnThoat.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {int ret=JOptionPane.showConfirmDialog(null, "Mun thot h?", "Thot", JOptionPane.YES_NO_OPTION);if(ret==JOptionPane.YES_OPTION)System.exit(0);}});btnXoa.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {txta.setText("");txtb.setText("");txtkq.setText("");txta.requestFocus();}});btnGiai.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {String sa=txta.getText();int a=0,b=0;try{a=Integer.parseInt(sa);}catch(Exception ex){JOptionPane.showMessageDialog(null, "Nhp sai nh dng!");txta.selectAll();txta.requestFocus();return;}String sb=txtb.getText();try{b=Integer.parseInt(sb);}catch(Exception ex){JOptionPane.showMessageDialog(null, "Nhp sai nh dng!");txtb.selectAll();txtb.requestFocus();return;}double kq=0;if(radCong.isSelected()){kq=(a+b);}else if(radTru.isSelected()){kq=(a-b);}else if(radNhan.isSelected()){kq=(a*b);}else{kq=a*1.0/b*1.0;}txtkq.setText(kq+"");}});Container con=getContentPane();con.add(pnBorder);}public static void main(String[] args) {CongTruNhanChiaUI ui=new CongTruNhanChiaUI("Cng - Tr - Nhn - Chia");ui.doShow();}}

Bi tp 7: Thao tc trn JList JcheckboxThit k giao din nh hnh bn di v thc hin cc thao tc theo yu cu:

Chng trnh cho php nhp vo cc s nguyn t giao din trong phn nhp thng tin, Khi ngi s nhp gi tr vo JTextField v click nt Nhp th s cp nhp d liu xung JList, Nu checked vo Cho nhp s m th cc s m mi c php a vo JList cn khng th thng bo li. Chn tc v, sinh vin phi thc hin ton b cc yu cu Nt ng chng trnh: s hin th thng bo hi ngi s dng c mun ng hay khng.

Bi tp 8: Vit chng trnh qun l sn phmYu cu chc nng: Cho php nhp/ xut danh mc, danh sch sn phm Cho php cp nht thng tin Cho php lu / c danh mc sn phm Yu cu s dng JMenuBar, JList, JTable, JCombobox,

Menu Write Data to disk dng lu d liu xung cngMenu Open Data from disk c d li t cngMenu Exit dng thot chng trnh

Cch lu/ c i tng trn cng: Tt c cc class phi implements Serializable: public class Sanpham implements Serializable{} public class DanhMucSanPham implements Serializable{} Vit mt class MyFile c 2 phng thc: Lu i tng:public static void luuDoiTuong(Object obj, String fileName){try{FileOutputStream fOut=new FileOutputStream(fileName);ObjectOutputStream out=new ObjectOutputStream(fOut);out.writeObject(obj);out.close();}catch(Exception ex){ex.printStackTrace();} } c i tngpublic static Object docDoiTuong(String fileName){try{FileInputStream fIn=new FileInputStream(fileName);ObjectInputStream in=new ObjectInputStream(fIn);Object o=in.readObject();in.close();return o;}catch(Exception ex){ex.printStackTrace();}return null; } Trong testMain: DanhMucSanPham dsDienTu=(DanhMucSanPham )MyFile.docDoiTuong("luuluu.data");if(dsDienTu!=null)System.out.println(dsDienTu);MyFile.luuDoiTuong(dsDienTu, "luuluu.data");Bi tp 9: Thc hnh v Timer class (*)Dng class Timer thit k ng dng ImageAnimation.Giao din s c 2 JButton: Start v Stop. Khi bm Start chng trnh s hin th hnh nh tun t trong mng 10 hnh nh c sn. Bm Stop tm dng duyt hnh nh. Xem hnh yu cu

Hng dn: Dng CardLayout v Timerimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class ImageAnimation extends JFrame{private static final long serialVersionUID = 1L;Timer timer;private int pos=1;public ImageAnimation(String title){super(title);timer=new Timer(500, null);}public void doShow(){setSize(500,550);setLocationRelativeTo(null);setDefaultCloseOperation(EXIT_ON_CLOSE);addControl();setVisible(true);}public void addControl(){JPanel pnBorder=new JPanel();pnBorder.setLayout(new BorderLayout());JPanel pnNorth=new JPanel();JButton btnStart=new JButton("Start");JButton btnStop=new JButton("Stop");pnNorth.add(btnStart);pnNorth.add(btnStop);pnBorder.add(pnNorth,BorderLayout.NORTH);final JPanel pnCenter=new JPanel();pnCenter.setLayout(new CardLayout());pnBorder.add(pnCenter,BorderLayout.CENTER);pnCenter.setBackground(Color.RED);JPanel []pnArr=new JPanel[10];addImage(pnCenter,pnArr);showImage(pnCenter,"card1");btnStart.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {timer.start();timer.addActionListener(new TimerPanel(pnCenter));}});btnStop.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {timer.stop();}});Container con=getContentPane();con.add(pnBorder);}private void addImage(JPanel pnCenter,JPanel []pnArr){for(int i=0;i=10)pos=1;}}public static void main(String[] args) {;ImageAnimation imgUi=new ImageAnimation("Image Animation!");imgUi.doShow();}}Bi tp 10: Ci tin bi tp 10. Chng trnh s cho php c danh sch cc hnh nh bt k trong a. (*)

Hng dn:import java.awt.*;import java.awt.event.*;import java.io.File;

import javax.swing.*;public class ImageAnimation2 extends JFrame{private static final long serialVersionUID = 1L;Timer timer;private int pos=0;public ImageAnimation2(String title){super(title);timer=new Timer(500, null);}public void doShow(){setSize(500,550);setLocationRelativeTo(null);setDefaultCloseOperation(EXIT_ON_CLOSE);addControl();setVisible(true);}public void addControl(){JPanel pnBorder=new JPanel();pnBorder.setLayout(new BorderLayout());JPanel pnNorth=new JPanel();JButton btnBrowser=new JButton("Browser");JButton btnStart=new JButton("Start");JButton btnStop=new JButton("Stop");pnNorth.add(btnBrowser);pnNorth.add(btnStart);pnNorth.add(btnStop);pnBorder.add(pnNorth,BorderLayout.NORTH);

final JPanel pnCenter=new JPanel();pnCenter.setLayout(new CardLayout());pnBorder.add(pnCenter,BorderLayout.CENTER);pnCenter.setBackground(Color.RED);

btnStart.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {timer.start();timer.addActionListener(new TimerPanel(pnCenter));}});

btnStop.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {timer.stop();}});btnBrowser.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent arg0) {JFileChooser jfc=new JFileChooser();jfc.setMultiSelectionEnabled(true);if(jfc.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){File []files=jfc.getSelectedFiles();for(int i=0;i< files.length;i++){File f=files[i];ImageIcon icon=new ImageIcon(f.getPath());JPanel pn=new JPanel();JLabel lbl=new JLabel(icon);pn.add(lbl);pnCenter.add(pn,"card"+i);}showImage(pnCenter, "card0");}}});Container con=getContentPane();con.add(pnBorder);}public void showImage(JPanel pn,String cardName){CardLayout cl=(CardLayout)pn.getLayout();cl.show(pn, cardName);}private class TimerPanel implements ActionListener{JPanel pn=null;public TimerPanel(JPanel pn) {this.pn=pn;}public void actionPerformed(ActionEvent arg0) {showImage(pn,"card"+pos);pos++;if(pos>=pn.getComponentCount())pos=0;}}public static void main(String[] args) {;ImageAnimation2 imgUi=new ImageAnimation2("Image Animation!");imgUi.doShow();}}Bi tp 11: Thc hnh v to Menu. Yu cu thit k Menu theo hnh sau, ng vi mi menu item sinh vin hy ci t coding hin th thng bo l ang chn menu no. (*)Hng dn: JMenuBarJMenuJMenuItem. Phi bit kt hp cc class ny.MenuBar s add Menu, Menu s add MenuItem, ri gi setJMenuBar(menuBar);Yu cu gi lp Menu ging nh chng trnh Foxit Reader:

Menu File c giao din nh trn

Menu Edit c giao din nh trnBi tp 12: Thc hnh v JToolBar, tng t nh cu 12, gi lp Toolbar ca chng trnh Foxit Reader, ng vi mi lnh trn JToolBar, sinh vin hy xutt thng bo ang s dng chc nng no. (*)Hng dn: to cc JButton ri add vo JToolBar

Bi tp 13: Thit k giao din nh hnh bn di - JTable: (*)

package baitap13;

import java.awt.BorderLayout;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

import javax.swing.BoxLayout;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTable;import javax.swing.JTextField;import javax.swing.table.DefaultTableModel;

public class AccUI {

JFrame myFrame=new JFrame("Account");JTextField txtAccNumber;JTextField txtAccName;JTextField txtAccMoney;JTable tblAcc;DefaultTableModel tblModelAcc;JButton btnAdd,btnClear,btnExit;public AccUI(){JPanel pnAccNumber=new JPanel();pnAccNumber.setLayout(new BoxLayout(pnAccNumber, BoxLayout.X_AXIS));JLabel lblAccNumber=new JLabel("Account Number:");pnAccNumber.add(lblAccNumber);txtAccNumber=new JTextField(15);pnAccNumber.add(txtAccNumber);JPanel pnAccName=new JPanel();pnAccName.setLayout(new BoxLayout(pnAccName, BoxLayout.X_AXIS));JLabel lblAccName=new JLabel("Account Name:");pnAccName.add(lblAccName);txtAccName=new JTextField(15);pnAccName.add(txtAccName);JPanel pnAccMoney=new JPanel();pnAccMoney.setLayout(new BoxLayout(pnAccMoney, BoxLayout.X_AXIS));JLabel lblAccMoney=new JLabel("Account Money:");pnAccMoney.add(lblAccMoney);txtAccMoney=new JTextField(15);pnAccMoney.add(txtAccMoney);Container con=myFrame.getContentPane();con.setLayout(new BorderLayout());JPanel pInfor=new JPanel();pInfor.setLayout(new BoxLayout(pInfor, BoxLayout.Y_AXIS));pInfor.add(pnAccNumber);pInfor.add(pnAccName);pInfor.add(pnAccMoney);con.add(pInfor,BorderLayout.NORTH);tblModelAcc=new DefaultTableModel();tblModelAcc.addColumn("Acc Number");tblModelAcc.addColumn("Acc Name");tblModelAcc.addColumn("Acc Money");tblAcc=new JTable(tblModelAcc);JScrollPane sc=new JScrollPane(tblAcc,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);con.add(sc,BorderLayout.CENTER);JPanel pnButton=new JPanel();btnAdd=new JButton("Add");btnAdd.setMnemonic('A');btnClear=new JButton("Clear");btnClear.setMnemonic('C');btnExit=new JButton("Exit");btnExit.setMnemonic('E');pnButton.add(btnAdd);pnButton.add(btnClear);pnButton.add(btnExit);con.add(pnButton,BorderLayout.SOUTH);lblAccName.setPreferredSize(lblAccNumber.getPreferredSize());lblAccMoney.setPreferredSize(lblAccNumber.getPreferredSize());addEvents();}public void addEvents(){btnAdd.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stubString arr[]={txtAccNumber.getText(),txtAccName.getText(),txtAccMoney.getText()};tblModelAcc.addRow(arr);}});btnExit.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {// TODO Auto-generated method stub int ret=JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit!", JOptionPane.YES_NO_OPTION); if(ret==JOptionPane.YES_OPTION) System.exit(0);}});}public void doShow(){myFrame.setSize(400, 300);myFrame.setLocationRelativeTo(null);myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);myFrame.setVisible(true);}}package baitap13;

public class TestAccount {

/** * @param args */public static void main(String[] args) {AccUI ui=new AccUI();ui.doShow();}

}MODULE 2Mc ch:Thc hnh MultiThreading, hiu c Thread, Runnable, Swings vi Threading

Bi tp 1: To mt Thread k tha t Thread class

Bi tp 2: To mt Thread implements t Runnable interface

Bi tp 3: Hin th cc trng thi trong Thread

Bi tp 4: Kim tra currentThread, acctiveCount v isAlive

Bi tp 5: Thit lp u tin cho Thread (dng phng thc setPriority), c 3 u tin cn bn : MAX_PRIORITY (10), NORM_PRIORITY(5), MIN_PRIORITY(1). Chng ta c th thit lp u tin ty t 1 ti 10.

Bi tp 6: Thc hnh v Deamon Thread

Bi tp 7: Hy vit chng trnh Demo chuyn khon ngn hngYu cu : Phi ng b d liu gia cc ln gi tin / Rt tinMc ch : Hiu c Race Condition, ReentrantLock , synchronized

V d v Race Condition.Class Bank/** A bank with a number of bank accounts. */public class Bank {/** Constructs the bank. @param n the number of accounts @param initialBalance the initial balance for each account */ public Bank(int n, double initialBalance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialBalance; }

/** Transfers money from one account to another. @param from the account to transfer from @param to the account to transfer to @param amount the amount to transfer */ public void transfer(int from, int to, double amount) { if (accounts[from] < amount) return; System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); }

/** Gets the sum of all account balances. @return the total balance */ public double getTotalBalance() { double sum = 0;

for (double a : accounts) sum += a;

return sum; }

/** Gets the number of accounts in the bank. @return the number of accounts */ public int size() { return accounts.length; }

private final double[] accounts;}

Class TransferRunnable/** A runnable that transfers money from an account to other accounts in a bank. */public class TransferRunnable implements Runnable {

/** Constructs a transfer runnable. @param b the bank between whose account money is transferred @param from the account to transfer money from @param max the maximum amount of money in each transfer */public TransferRunnable(Bank b, int from, double max){bank = b;fromAccount = from;maxAmount = max;}

public void run(){try{while (true){int toAccount = (int) (bank.size() * Math.random());double amount = maxAmount * Math.random();bank.transfer(fromAccount, toAccount, amount);Thread.sleep((int) (DELAY * Math.random()));}}catch (InterruptedException e) {}}

private Bank bank;private int fromAccount;private double maxAmount;private int DELAY = 10;

}

Class UnsynchBankTestpublic class UnsynchBankTest{ public static void main(String[] args) { Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); int i; for (i = 0; i < NACCOUNTS; i++) { TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE); Thread t = new Thread(r); t.start(); } } public static final int NACCOUNTS = 100; public static final double INITIAL_BALANCE = 1000; }

Kt qu ta thy d liu khng c ng b, cho du chuyn / nhn sy ra th tng tin cng phi gi nguyn, y n b thay i, nguyn nhn gy ra l do Race Condition

Chng ta sa li hm run :

Kt qu l gi liu c ng b

Chng ta c th ng b bng cch tip cn ReentrantLock. Di y l code minh ha:

Class Bankimport java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;

/**A bank with a number of bank accounts.*/public class Bank {/** Constructs the bank. @param n the number of accounts @param initialBalance the initial balance for each account */ public Bank(int n, double initialBalance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialBalance; bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); }

/** Transfers money from one account to another. @param from the account to transfer from @param to the account to transfer to @param amount the amount to transfer */ public void transfer(int from, int to, double amount) throws InterruptedException { bankLock.lock(); try { while (accounts[from] < amount) sufficientFunds.await(); System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); sufficientFunds.signalAll(); } finally { bankLock.unlock(); } }

/** Gets the sum of all account balances. @return the total balance */ public double getTotalBalance() { bankLock.lock(); try { double sum = 0;

for (double a : accounts) sum += a;

return sum; } finally { bankLock.unlock(); } }

/** Gets the number of accounts in the bank. @return the number of accounts */ public int size() { return accounts.length; }

private final double[] accounts; private Lock bankLock; private Condition sufficientFunds;}

Class TransferRunnable/** A runnable that transfers money from an account to other accounts in a bank.*/public class TransferRunnable implements Runnable {

/** Constructs a transfer runnable. @param b the bank between whose account money is transferred @param from the account to transfer money from @param max the maximum amount of money in each transfer */ public TransferRunnable(Bank b, int from, double max) { bank = b; fromAccount = from; maxAmount = max; }

public void run() { try { while (true) { int toAccount = (int) (bank.size() * Math.random()); double amount = maxAmount * Math.random(); bank.transfer(fromAccount, toAccount, amount); Thread.sleep((int) (DELAY * Math.random())); } } catch (InterruptedException e) {} }

private Bank bank; private int fromAccount; private double maxAmount; private int DELAY = 10;

}

Class SynchBankTest/** This program shows how multiple threads can safely access a data structure.*/public class SynchBankTest{ public static void main(String[] args) { Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); int i; for (i = 0; i < NACCOUNTS; i++) { TransferRunnable r = new TransferRunnable(b, i, INITIAL_BALANCE); Thread t = new Thread(r); t.start(); } }

public static final int NACCOUNTS = 100; public static final double INITIAL_BALANCE = 1000; }

Bi tp 8 : Tip tc vi bi chuyn khon cu 7, yu cu thit k giao din nh hnh di y thc hin chc nng chuyn khon. Bm vo Start chng trnh s tin hnh chuyn khon trn giao din, khi bm Stop chng trnh s dng chuyn khon.

Bi tp 9: Dng a tin trnh cp nhp d liu cho JProgressBar. Giao din chng trnh nh bn di.

Coding mu :import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.Border;class myRun implements Runnable{JProgressBar proBar=null;public myRun(JProgressBar bar){proBar=bar;}public void run() {int x=0;while(x