例8.1应用程序用Thread子类实现多线程。
import java.util.Date; public class Example8_1 { static Athread threadA; static Bthread threadB; public static void main(String args[]) { threadA = new Athread(); threadB = new Bthread(); threadA.start(); threadB.start(); } } class Athread extends Thread { public void run() { Date timeNow;// 为了能输出当时的时间 for (int i = 0; i <= 5; i++) { timeNow = new Date();// 得到当前时间 System.out.println("我是threadA:" + timeNow.toString()); try { sleep(2000); } catch (InterruptedException e) { } } } } class Bthread extends Thread { public void run() { Date timeNow; for (int i = 0; i <= 5; i++) { timeNow = new Date(); System.out.println("我是threadB:" + timeNow.toString()); try { sleep(1000); } catch (InterruptedException e) { } } } }
例8.2小应用程序通过Runnable接口创建线程。
import java.applet.*; import java.awt.*; import javax.swing.*; public class Example8_2 extends java.applet.Applet implements Runnable {// 实现Runnable接口 Thread myThread = null;// 声明线程对象 JTextArea t; int k; public void start() { t = new JTextArea(20, 20); add(t); k = 0; setSize(500, 400); if (myThread == null)// 重新进入小程序时,再次创建线程myThread { myThread = new Thread(this);// 创建新线程 myThread.start();// 启动新线程 } } public void run()// 定义线程的运行代码 { while (myThread != null) { try { myThread.sleep(1000); k++; } catch (InterruptedException e) { } repaint(); } } public void paint(Graphics g) { double i = Math.random(); if (i < 0.5) { g.setColor(Color.yellow); } else { g.setColor(Color.blue); } g.fillOval(10, 10, (int) (100 * i), (int) (100 * i)); t.append("我在工作,已休息了" + k + "次 "); } public void stop()// 离开小程序页时,调用本方法,让线程停止 { if (myThread != null) { myThread.stop(); myThread = null;// 重新进入小程序页时,再次创建线程myThread } } }
例8.3小应用程序创建两个线程,一个顺时针画图,另一个逆时针画图。
import java.applet.*; import java.awt.*; import java.awt.event.*; public class Example8_3 extends java.applet.Applet implements Runnable { Thread redBall, blueBall; Graphics redPen, bulePen; int blueSeta = 0, redSeta = 0; public void init() { setSize(250, 200); redBall = new Thread(this); blueBall = new Thread(this); redPen = getGraphics(); bulePen = getGraphics(); redPen.setColor(Color.red); bulePen.setColor(Color.blue); setBackground(Color.gray); } public void start() { redBall.start(); blueBall.start(); } public void run() { int x, y; while (true) { if (Thread.currentThread() == redBall) { x = (int) (80.0 * Math.cos(3.1415926 / 180.0 * redSeta)); y = (int) (80.0 * Math.sin(3.1415926 / 180.0 * redSeta)); redPen.setColor(Color.gray);// 用底色画图,擦除原先所画圆点 redPen.fillOval(100 + x, 100 + y, 10, 10); redSeta += 3; if (redSeta >= 360) { redSeta = 0; } x = (int) (80.0 * Math.cos(3.1415926 / 180.0 * redSeta)); y = (int) (80.0 * Math.sin(3.1415926 / 180.0 * redSeta)); redPen.setColor(Color.red); redPen.fillOval(100 + x, 100 + y, 10, 10); try { redBall.sleep(20); } catch (InterruptedException e) { } } else if (Thread.currentThread() == blueBall) { x = (int) (80.0 * Math.cos(3.1415926 / 180.0 * blueSeta)); y = (int) (80.0 * Math.sin(3.1415926 / 180.0 * blueSeta)); bulePen.setColor(Color.gray); bulePen.fillOval(150 + x, 100 + y, 10, 10); blueSeta -= 3; if (blueSeta <= -360) { blueSeta = 0; } x = (int) (80.0 * Math.cos(3.1415926 / 180.0 * blueSeta)); y = (int) (80.0 * Math.sin(3.1415926 / 180.0 * blueSeta)); bulePen.setColor(Color.blue); bulePen.fillOval(150 + x, 100 + y, 10, 10); try { blueBall.sleep(40); } catch (InterruptedException e) { } } } } }
例8.4应用程序说明多线程共享变量,因没有互相协调产生不正确结果。
public class Example8_4 { public static void main(String args[]) { MyResourceClass mrc = new MyResourceClass(); Thread[] aThreadArray = new Thread[20]; System.out.println(" 刚开始的值是:" + mrc.getInfo()); // 20个线程*每个线程加1000次*每次加50 System.out.println(" 预期的正确结果是:" + 20 * 1000 * 50); System.out.println(" 多个线程正在工作,请稍等!"); for (int i = 0; i < 20; i++)// 产生20个线程并开始执行 { aThreadArray[i] = new Thread(new MyMultiThreadClass(mrc)); aThreadArray[i].start(); } WhileLoop: // 等待所有线程结束 while (true) { for (int i = 0; i < 20; i++) { if (aThreadArray[i].isAlive()) { continue WhileLoop; } } break; } System.out.println(" 最后的结果是:" + mrc.getInfo()); } } class MyMultiThreadClass implements Runnable { MyResourceClass UseInteger; MyMultiThreadClass(MyResourceClass mrc) { UseInteger = mrc; } public void run() { int i, LocalInteger; for (i = 0; i < 1000; i++) { LocalInteger = UseInteger.getInfo();// 把值取出来 LocalInteger += 50; try { Thread.sleep(10);// 做一些其他的处理 } catch (InterruptedException e) { } UseInteger.putInfo(LocalInteger);// 把值存出来 } } } class MyResourceClass { int IntegerResource; MyResourceClass() { IntegerResource = 0; } public int getInfo() { return IntegerResource; } public void putInfo(int info) { IntegerResource = info; } }
例8.5小应用程序模拟一群顾客购买纪念品。
class SalesLady { int memontoes, five, ten;// 销售员纪念品数,5、10元张数 public synchronized String ruleForSale(int num, int money) { // 购买过程为临界段 String s = null; if (memontoes == 0) { return "对不起,已售完!"; } if (money == 5) { memontoes--; five++; s = "给你一个纪念品," + "你的钱正好。";// 销售员的回答 } else if (money == 10) { while (five < 1) { try { System.out.println("" + num + "号顾客用10元钱购票,发生等待!"); wait(); } catch (InterruptedException e) { } } memontoes--; five -= 1; ten++; s = "给你一个纪念品," + "你给了十元,找你五元。"; } notify();// 通知后面等待的顾客 return s; } SalesLady(int m, int f, int t) { memontoes = m; five = f; ten = t; } } public class Example8_5 extends java.applet.Applet { static SalesLady salesLady = new SalesLady(14, 0, 0); public void start() { int moneies[] = { 10, 10, 5, 10, 5, 10, 5, 5, 10, 5, 10, 5, 5, 10, 5 }; Thread[] aThreadArray = new Thread[20]; System.out.println("现在开始购票:"); for (int i = 0; i < moneies.length; i++)// 产生20个线程并开始执行 { aThreadArray[i] = new Thread(new CustomerClass(i + 1, moneies[i])); aThreadArray[i].start(); } WhileLoop: // 等待所有线程结束 while (true) { for (int i = 0; i < moneies.length; i++) { if (aThreadArray[i].isAlive()) { continue WhileLoop; } } break; } System.out.println("购票结束"); } } class CustomerClass implements Runnable { int num, money;// 顾客序号,钱的面值 public void run() { try { Thread.sleep(10); } // 假定顾客在购买前还做一些其他的事 catch (InterruptedException e) { } System.out.println("我是" + num + "号顾客,用" + money + "元购纪念品,售货员说:" + Example8_5.salesLady.ruleForSale(num, money)); } CustomerClass(int n, int m) { num = n; money = m; }// 顾客构造方法 }