第十六週總結java
1、知識總結編程
方式1:繼承java.lang.Thread類,並覆蓋run()方法。優點:編寫簡單;劣勢:沒法繼承其餘父類安全
方式2:實現java.lang.Runnable接口,並實現run()方法。優點:能夠繼承其餘類,多線程能夠共享同一個Thread對象;劣勢:編程方式稍微複雜,如需訪問當前線程,需調用Thread.currentThread()方法數據結構
兩種方法的區別多線程
1) start:併發
用start方法來啓動線程,真正實現了多線程運行,這時無需等待run方法體代碼執行完畢而直接繼續執行下面的代碼。經過調用Thread類的start()方法來啓動一個線程,這時此線程處於就緒(可運行)狀態,並無運行,一旦獲得cpu時間片,就開始執行run()方法,這裏方法run()稱爲線程體,它包含了要執行的這個線程的內容,Run方法運行結束,此線程隨即終止。框架
2) run:dom
run()方法只是類的一個普通方法而已,若是直接調用run方法,程序中依然只有主線程這一個線程,其程序執行路徑仍是隻有一條,仍是要順序執行,仍是要等待jvm
run方法體執行完畢後纔可繼續執行下面的代碼,這樣就沒有達到寫線程的目的。ide
總結:調用start方法方可啓動線程,而run方法只是thread的一個普通方法調用,仍是在主線程裏執行。
這兩個方法應該都比較熟悉,把須要並行處理的代碼放在run()方法中,start()方法啓動線程將自動調用 run()方法,這是由jvm的內存機制規定的。而且run()方法必須是public訪問權限,返回值類型爲void。
兩種方式的比較 :
實際中每每採用實現Runable接口,一方面由於java只支持單繼承,繼承了Thread類就沒法再繼續繼承其它類,並且Runable接口只有一個run方法;另外一方面經過結果能夠看出實現Runable接口才是真正的多線程。
線程是一個動態執行的過程,它也有一個從生產到死亡的過程。
(1)生命週期的五種狀態
當建立Thread類的一個實例(對象)時,此線程進入新建狀態(未被啓動)。
例如:Thread t1 = new Threade();
線程已經被啓動(start),正在等待分配CPU時間片,也就是說此事線程正在就緒隊列中排隊等候獲得CPU資源。
例如:t1.start();
運行(running)
線程得到cpuz資源正在執行任務(run()方法),此時除非線程自動放棄CPU資源或者有優先級更高的的線程進入,線程將一直運行到結束!
當線程執行完畢或被其它線程殺死,線程就進入死亡狀態,這時線程不可能再進入就緒狀態等待執行。
天然終止:正常運行run()方法後終止
異常終止:調用stop()方法讓一個線程終止運行
因爲某種緣由致使正在運行的線程讓出CPU並暫停本身的執行,即進入堵塞狀態。
正在睡眠:用sleep(long t) 方法可以使線程進入睡眠方式。一個睡眠着的線程在指定的時間過去可進入就緒狀態。
正在等待:調用wait()方法。(調用notify()方法回到就緒狀態)
被另外一個線程所阻塞:調用suspend()方法。(調用resume()方法恢復)
當多個線程訪問同一個數據時,容易出現線程安全問題,須要某種方式來確保資源在某一時刻只被一個線程使用。須要讓線程同步,保證數據安全
線程同步的實現方案:同步代碼塊和同步方法,均須要使用synchronized關鍵字
線程同步的好處:解決了線程安全問題
線程同步的缺點:性能降低,可能會帶來死鎖
Java中每一個對象都有一個內置鎖。
當程序運行到非靜態的synchronized同步方法上時,自動得到與正在執行代碼類的當前實例(this實例)有關的鎖。得到一個對象的鎖也稱爲獲取鎖、鎖定對象、在對象上鎖定或在對象上同步。
當程序運行到synchronized同步方法或代碼塊時才該對象鎖才起做用。
一個對象只有一個鎖。因此,若是一個線程得到該鎖,就沒有其餘線程能夠得到鎖,直到第一個線程釋放(或返回)鎖。這也意味着任何其餘線程都不能進入該對象上的synchronized方法或代碼塊,直到該鎖被釋放。
釋放鎖是指持鎖線程退出了synchronized同步方法或代碼塊。
關於鎖和同步,有一下幾個要點:
1)、只能同步方法,而不能同步變量和類;
2)、每一個對象只有一個鎖;當提到同步時,應該清楚在什麼上同步?也就是說,在哪一個對象上同步?
3)、沒必要同步類中全部的方法,類能夠同時擁有同步和非同步方法。
4)、若是兩個線程要執行一個類中的synchronized方法,而且兩個線程使用相同的實例來調用方法,那麼一次只能有一個線程可以執行方法,另外一個須要等待,直到鎖被釋放。也就是說:若是一個線程在對象上得到一個鎖,就沒有任何其餘線程能夠進入(該對象的)類中的任何一個同步方法。
5)、若是線程擁有同步和非同步方法,則非同步方法能夠被多個線程自由訪問而不受鎖的限制。
6)、線程睡眠時,它所持的任何鎖都不會釋放。
7)、線程能夠得到多個鎖。好比,在一個對象的同步方法裏面調用另一個對象的同步方法,則獲取了兩個對象的同步鎖。
8)、同步損害併發性,應該儘量縮小同步範圍。同步不但能夠同步整個方法,還能夠同步方法中一部分代碼塊。
9)、在使用同步代碼塊時候,應該指定在哪一個對象上同步,也就是說要獲取哪一個對象的鎖。例如:
public int fix(int y) {
synchronized (this) {
x = x - y;
}
return x;
}
固然,同步方法也能夠改寫爲非同步方法,但功能徹底同樣的,例如:
public synchronized int getX() {
return x++;
}
與
public int getX() {
synchronized (this) {
return x;
}
}
效果是徹底同樣的。
sleep()是讓某個線程暫停運行一段時間,其控制範圍是由當前線程決定,也就是說,在線程裏面決定.比如如說,我要作的事情是 "點火->燒水->煮麪",而當我點完火以後我不當即燒水,我要休息一段時間再燒.對於運行的主動權是由個人流程來控制。
而wait(),首先,這是由某個肯定的對象來調用的,將這個對象理解成一個傳話的人,當這我的在某個線程裏面說"暫停!",也是 thisObj.wait(),這裏的暫停是阻塞,仍是"點火->燒水->煮飯",thisObj就比如一個監督個人人站在我旁邊,原本該線 程應該執行1後執行2,再執行3,而在2處被那個對象喊暫停,那麼我就會一直等在這裏而不執行3,但正個流程並無結束,我一直想去煮飯,但還沒被容許, 直到那個對象在某個地方說"通知暫停的線程啓動!",也就是thisObj.notify()的時候,那麼我就能夠煮飯了,這個被暫停的線程就會從暫停處 繼續執行。
其實二者均可以讓線程暫停一段時間,可是本質的區別是一個線程的運行狀態控制,一個是線程之間的通信的問題。
2、實驗部分——線程技術
1、實驗目的與要求
(1) 掌握線程概念;
(2) 掌握線程建立的兩種技術;
(3) 理解和掌握線程的優先級屬性及調度方法;
(4) 掌握線程同步的概念及實現技術;
2、實驗內容和步驟
實驗1:測試程序並進行代碼註釋。
測試程序1:
l 在elipse IDE中調試運行ThreadTest,結合程序運行結果理解程序;
l 掌握線程概念;
l 掌握用Thread的擴展類實現線程的方法;
l 利用Runnable接口改造程序,掌握用Runnable接口建立線程的方法。
class Lefthand extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("You are Students!"); try{ sleep(500); } catch(InterruptedException e) { System.out.println("Lefthand error.");} } } } class Righthand extends Thread { public void run() { for(int i=0;i<=5;i++) { System.out.println("I am a Teacher!"); try{ sleep(300); } catch(InterruptedException e) { System.out.println("Righthand error.");} } } } public class ThreadTest { static Lefthand left; static Righthand right; public static void main(String[] args) { left=new Lefthand(); right=new Righthand(); left.start(); right.start(); } } |
修改後的代碼
class Lefthand implements Runnable { public void run() { for (int i = 0; i <= 5; i++) { System.out.println("You are Students!"); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println("Lefthand error."); } } } } class Righthand implements Runnable { public void run() { for (int i = 0; i <= 5; i++) { System.out.println("I am a Teacher!"); try { Thread.sleep(300); } catch (InterruptedException e) { System.out.println("Righthand error."); } } } } public class ThreadTest { public static void main(String[] args) { Runnable left = new Lefthand(); Thread a = new Thread(left); Runnable right = new Righthand(); Thread b = new Thread(right); a.start(); b.start(); } }
測試程序2:
l 在Elipse環境下調試教材625頁程序14-一、14-2 、14-3,結合程序運行結果理解程序;
l 在Elipse環境下調試教材631頁程序14-4,結合程序運行結果理解程序;
l 對比兩個程序,理解線程的概念和用途;
l 掌握線程建立的兩種技術。
package bounceThread; import java.awt.geom.*; /** A ball that moves and bounces off the edges of a rectangle * @version 1.33 2007-05-17 * @author Cay Horstmann */ public class Ball { private static final int XSIZE = 15; private static final int YSIZE = 15; private double x = 0; private double y = 0; private double dx = 1; private double dy = 1; /** Moves the ball to the next position, reversing direction if it hits one of the edges */ //定義了移動方法 public void move(Rectangle2D bounds) { x += dx; y += dy; if (x < bounds.getMinX()) { x = bounds.getMinX(); dx = -dx; } if (x + XSIZE >= bounds.getMaxX()) { x = bounds.getMaxX() - XSIZE; dx = -dx; } if (y < bounds.getMinY()) { y = bounds.getMinY(); dy = -dy; } if (y + YSIZE >= bounds.getMaxY()) { y = bounds.getMaxY() - YSIZE; dy = -dy; } } /** Gets the shape of the ball at its current position. */ //定義球外形 public Ellipse2D getShape() { return new Ellipse2D.Double(x, y, XSIZE, YSIZE); } }
package bounce; import java.awt.*; import java.util.*; import javax.swing.*; /** * The component that draws the balls. * @version 1.34 2012-01-26 * @author Cay Horstmann */ public class BallComponent extends JPanel { private static final int DEFAULT_WIDTH = 450; private static final int DEFAULT_HEIGHT = 350; private java.util.List<Ball> balls = new ArrayList<>(); /** * Add a ball to the component. * @param b the ball to add */ public void add(Ball b) { balls.add(b); } public void paintComponent(Graphics g) { super.paintComponent(g); // erase background Graphics2D g2 = (Graphics2D) g; for (Ball b : balls) { g2.fill(b.getShape()); } } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } }
package bounce; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Shows an animated bouncing ball. * @version 1.34 2015-06-21 * @author Cay Horstmann */ public class Bounce { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new BounceFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } /** * The frame with ball component and buttons. */ class BounceFrame extends JFrame { private BallComponent comp; public static final int STEPS = 1000; public static final int DELAY = 3; /** * Constructs the frame with the component for showing the bouncing ball and * Start and Close buttons */ public BounceFrame() { setTitle("Bounce"); comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", event -> addBall());//將按鈕放入buttonPanel addButton(buttonPanel, "Close", event -> System.exit(0)); add(buttonPanel, BorderLayout.SOUTH);//將buttonPanel放入邊界管理器的南端 pack(); } /** * Adds a button to a container. * @param c the container * @param title the button title * @param listener the action listener for the button */ public void addButton(Container c, String title, ActionListener listener) { //生成按鈕對象 JButton button = new JButton(title); c.add(button); button.addActionListener(listener);//註冊監聽器事件 } /** * Adds a bouncing ball to the panel and makes it bounce 1,000 times. */ public void addBall() { try { Ball ball = new Ball(); comp.add(ball); for (int i = 1; i <= STEPS; i++) { ball.move(comp.getBounds()); comp.paint(comp.getGraphics()); Thread.sleep(DELAY);//在兩個球顯示之間有延遲 } } catch (InterruptedException e)//中斷異常 { } } }
14-一、14-二、14-3,運行結果以下:(小球沒有停下的時候程序關閉不了)
package bounceThread; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * 顯示動畫彈跳球 * @version 1.34 2015-06-21 * @author Cay Horstmann */ public class BounceThread { public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame frame = new BounceFrame(); frame.setTitle("BounceThread"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } } /** * 框架與球組件和按鈕 */ class BounceFrame extends JFrame { private BallComponent comp; public static final int STEPS = 1000; public static final int DELAY = 5; /** * 用顯示彈跳球以及開始和關閉按鈕的組件構建框架 */ public BounceFrame() { comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", event -> addBall()); addButton(buttonPanel, "Close", event -> System.exit(0)); add(buttonPanel, BorderLayout.SOUTH); pack(); } /** * 向容器添加按鈕 * * @param c * the container * @param title * the button title * @param listener * the action listener for the button */ public void addButton(Container c, String title, ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); } /** * 在畫布上添加一個彈跳球,並啓動一個線程使其彈跳 */ public void addBall() { Ball ball = new Ball(); comp.add(ball); Runnable r = () -> { try { for (int i = 1; i <= STEPS; i++) { ball.move(comp.getBounds());//將球移動到下一個位置,若是碰到其中一個邊緣則反轉方向 comp.repaint();//重繪此組件。 Thread.sleep(DELAY);//在指定的毫秒數內讓當前正在執行的線程休眠 } } catch (InterruptedException e) { } }; Thread t = new Thread(r); t.start(); } }
14-4程序運行結果以下:(小球運動時程序也能夠被關閉)
測試程序3:分析如下程序運行結果並理解程序。
class Race extends Thread { public static void main(String args[]) { Race[] runner=new Race[4]; for(int i=0;i<4;i++) runner[i]=new Race( ); for(int i=0;i<4;i++) runner[i].start( ); runner[1].setPriority(MIN_PRIORITY); runner[3].setPriority(MAX_PRIORITY);} public void run( ) { for(int i=0; i<1000000; i++); System.out.println(getName()+"線程的優先級是"+getPriority()+"已計算完畢!"); } } |
測試程序4
l 教材642頁程序模擬一個有若干帳戶的銀行,隨機地生成在這些帳戶之間轉移錢款的交易。每個帳戶有一個線程。在每一筆交易中,會從線程所服務的帳戶中隨機轉移必定數目的錢款到另外一個隨機帳戶。
l 在Elipse環境下調試教材642頁程序14-五、14-6,結合程序運行結果理解程序;
package unsynch; import java.util.*; /** * 有許多銀行帳戶的銀行 * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { private final double[] accounts; /** * 建設銀行 * @param n 帳號 * @param initialBalance 每一個帳戶的初始餘額 */ public Bank(int n, double initialBalance) { accounts = new double[n]; Arrays.fill(accounts, initialBalance); } /** * 把錢從一個帳戶轉到另外一個帳戶 * @param from 轉帳帳戶從 * @param to 轉帳帳戶到 * @param amount 轉讓的數額 */ 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()); } /** * 獲取全部賬戶餘額的總和 * @return 總餘額 */ public double getTotalBalance() { double sum = 0; for (double a : accounts) sum += a; return sum; } /** * 獲取銀行中的賬戶數量 * @return 帳號 */ public int size() { return accounts.length; } }
package unsynch; /** * 此程序顯示多個線程訪問數據結構時的數據損壞 * @version 1.31 2015-06-21 * @author Cay Horstmann */ public class UnsynchBankTest { public static final int NACCOUNTS = 100; public static final double INITIAL_BALANCE = 1000; public static final double MAX_AMOUNT = 1000; public static final int DELAY = 10; public static void main(String[] args) { Bank bank = new Bank(NACCOUNTS, INITIAL_BALANCE); for (int i = 0; i < NACCOUNTS; i++) { int fromAccount = i; Runnable r = () -> { try { while (true) { int toAccount = (int) (bank.size() * Math.random()); double amount = MAX_AMOUNT * Math.random(); bank.transfer(fromAccount, toAccount, amount); Thread.sleep((int) (DELAY * Math.random())); } } catch (InterruptedException e) { } }; Thread t = new Thread(r); t.start(); } } }
綜合編程練習
編程練習1
(1) 用戶信息輸入界面以下圖所示:
(2) 用戶點擊提交按鈕時,用戶輸入信息顯示控制檯界面;
(3) 用戶點擊重置按鈕後,清空用戶已輸入信息;
(4) 點擊窗口關閉,程序退出。
package 編程二; import java.awt.EventQueue; import javax.swing.JFrame; public class Mian { public static void main(String[] args) { EventQueue.invokeLater(() -> { DemoJFrame page = new DemoJFrame(); }); } }
package 編程二; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.Window; public class WinCenter { public static void center(Window win){ Toolkit tkit = Toolkit.getDefaultToolkit(); Dimension sSize = tkit.getScreenSize(); Dimension wSize = win.getSize(); if(wSize.height > sSize.height){ wSize.height = sSize.height; } if(wSize.width > sSize.width){ wSize.width = sSize.width; } win.setLocation((sSize.width - wSize.width)/ 2, (sSize.height - wSize.height)/ 2); } }
package 編程二; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.LayoutManager; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; public class DemoJFrame extends JFrame { private JPanel jPanel1; private JPanel jPanel2; private JPanel jPanel3; private JPanel jPanel4; private JTextField fieldname; private JComboBox comboBox; private JTextField fieldadress; private ButtonGroup bg; private JRadioButton nan; private JRadioButton nv; private JCheckBox sing; private JCheckBox dance; private JCheckBox draw; public DemoJFrame() { // 設置窗口大小 this.setSize(800, 400); // 設置可見性 this.setVisible(true); // 設置標題 this.setTitle("編程練習一"); // 設置關閉操做 this.setDefaultCloseOperation(EXIT_ON_CLOSE); // 設置窗口居中 WinCenter.center(this); // 建立四個面板對象 jPanel1 = new JPanel(); setJPanel1(jPanel1); jPanel2 = new JPanel(); setJPanel2(jPanel2); jPanel3 = new JPanel(); setJPanel3(jPanel3); jPanel4 = new JPanel(); setJPanel4(jPanel4); // 設置容器的爲流佈局 FlowLayout flowLayout = new FlowLayout(); this.setLayout(flowLayout); // 將四個面板添加到容器中 this.add(jPanel1); this.add(jPanel2); this.add(jPanel3); this.add(jPanel4); } /* * 設置面一 */ private void setJPanel1(JPanel jPanel) { // TODO 自動生成的方法存根 jPanel.setPreferredSize(new Dimension(700, 45)); // 給面板的佈局設置爲網格佈局 一行4列 jPanel.setLayout(new GridLayout(1, 4)); JLabel name = new JLabel("姓名:"); name.setSize(100, 50); fieldname = new JTextField(""); fieldname.setSize(80, 20); JLabel study = new JLabel("學歷:"); comboBox = new JComboBox(); comboBox.addItem("初中"); comboBox.addItem("高中"); comboBox.addItem("本科"); jPanel.add(name); jPanel.add(fieldname); jPanel.add(study); jPanel.add(comboBox); } /* * 設置面板二 */ private void setJPanel2(JPanel jPanel) { // TODO 自動生成的方法存根 jPanel.setPreferredSize(new Dimension(700, 50)); // 給面板的佈局設置爲網格佈局 一行4列 jPanel.setLayout(new GridLayout(1, 4)); JLabel name = new JLabel("地址:"); fieldadress = new JTextField(); fieldadress.setPreferredSize(new Dimension(150, 50)); JLabel study = new JLabel("愛好:"); JPanel selectBox = new JPanel(); selectBox.setBorder(BorderFactory.createTitledBorder("")); selectBox.setLayout(new GridLayout(3, 1)); sing = new JCheckBox("唱歌"); dance = new JCheckBox("跳舞"); draw = new JCheckBox("畫畫"); selectBox.add(sing); selectBox.add(dance); selectBox.add(draw); jPanel.add(name); jPanel.add(fieldadress); jPanel.add(study); jPanel.add(selectBox); } /* * 設置面板三 */ private void setJPanel3(JPanel jPanel) { // TODO 自動生成的方法存根 jPanel.setPreferredSize(new Dimension(700, 150)); FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT); jPanel.setLayout(flowLayout); JLabel sex = new JLabel("性別:"); JPanel selectBox = new JPanel(); selectBox.setBorder(BorderFactory.createTitledBorder("")); selectBox.setLayout(new GridLayout(2, 1)); bg = new ButtonGroup(); nan = new JRadioButton("男"); nv = new JRadioButton("女"); bg.add(nan); bg.add(nv); selectBox.add(nan); selectBox.add(nv); jPanel.add(sex); jPanel.add(selectBox); } /* * 設置面板四 */ private void setJPanel4(JPanel jPanel) { // TODO 自動生成的方法存根 jPanel.setPreferredSize(new Dimension(700, 150)); FlowLayout flowLayout = new FlowLayout(FlowLayout.CENTER, 50, 10); jPanel.setLayout(flowLayout); jPanel.setLayout(flowLayout); JButton sublite = new JButton("提交"); JButton reset = new JButton("重置"); sublite.addActionListener((e) -> valiData()); reset.addActionListener((e) -> Reset()); jPanel.add(sublite); jPanel.add(reset); } /* * 提交數據 */ private void valiData() { // TODO 自動生成的方法存根 // 拿到數據 String name = fieldname.getText().toString().trim(); String xueli = comboBox.getSelectedItem().toString().trim(); String address = fieldadress.getText().toString().trim(); System.out.println(name); System.out.println(xueli); String hobbystring=""; if (sing.isSelected()) { hobbystring+="唱歌 "; } if (dance.isSelected()) { hobbystring+="跳舞 "; } if (draw.isSelected()) { hobbystring+="畫畫 "; } System.out.println(address); if (nan.isSelected()) { System.out.println("男"); } if (nv.isSelected()) { System.out.println("女"); } System.out.println(hobbystring); } /* * 重置 */ private void Reset() { // TODO 自動生成的方法存根 fieldadress.setText(null); fieldname.setText(null); comboBox.setSelectedIndex(0); sing.setSelected(false); dance.setSelected(false); draw.setSelected(false); bg.clearSelection(); } }
2.建立兩個線程,每一個線程按順序輸出5次「你好」,每一個「你好」要標明來自哪一個線程及其順序號。
class Lefthand implements Runnable { public void run() { for (int i = 1; i <= 5; i++) { System.out.println(i+"a.你好"); try { Thread.sleep(500); } catch (InterruptedException e) { System.out.println("error."); } } } } class Righthand implements Runnable { public void run() { for (int i = 1; i <= 5; i++) { System.out.println(i+"b.你好"); try { Thread.sleep(300); } catch (InterruptedException e) { System.out.println("error."); } } } } public class ThreadTest { static Thread left; static Thread right; public static void main(String[] args) { Runnable a = new Lefthand(); Runnable b = new Righthand(); left = new Thread(a); right = new Thread(b); left.start(); right.start(); } }
3、實驗總結
經過本次實驗,我大體掌握了線程的概念和線程建立的兩種技術,理解了線程的優先級屬性及調度方法,在學習過程當中我也意識到了多線程對java編程的重要性,必定好好學習這一章知識。