例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 + "次\n");
} 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("\t刚开始的值是:" + mrc.getInfo());
// 20个线程*每个线程加1000次*每次加50
System.out.println("\t预期的正确结果是:" + 20 * 1000 * 50);
System.out.println("\t多个线程正在工作,请稍等!");
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("\t最后的结果是:" + 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;
}// 顾客构造方法
}

04747_Java语言程序设计(一)_第8章_多线程的更多相关文章

  1. ArcGIS for Desktop入门教程_第七章_使用ArcGIS进行空间分析 - ArcGIS知乎-新一代ArcGIS问答社区

    原文:ArcGIS for Desktop入门教程_第七章_使用ArcGIS进行空间分析 - ArcGIS知乎-新一代ArcGIS问答社区 1 使用ArcGIS进行空间分析 1.1 GIS分析基础 G ...

  2. ArcGIS for Desktop入门教程_第六章_用ArcMap制作地图 - ArcGIS知乎-新一代ArcGIS问答社区

    原文:ArcGIS for Desktop入门教程_第六章_用ArcMap制作地图 - ArcGIS知乎-新一代ArcGIS问答社区 1 用ArcMap制作地图 作为ArcGIS for Deskto ...

  3. ArcGIS for Desktop入门教程_第四章_入门案例分析 - ArcGIS知乎-新一代ArcGIS问答社区

    原文:ArcGIS for Desktop入门教程_第四章_入门案例分析 - ArcGIS知乎-新一代ArcGIS问答社区 1 入门案例分析 在第一章里,我们已经对ArcGIS系列软件的体系结构有了一 ...

  4. 04747_Java语言程序设计(一)_第3章_面向对象编程基础

    链式编程 每次调用方法后,返回的是一个对象 /* * 链式编程 * 每次调用方法后,返回的是一个对象 */ class Student { public void study() { System.o ...

  5. 04747_Java语言程序设计(一)_第1章_Java语言基础

    二进制0b开头 八进制0开头 十六进制0x开头 package com.jacky; public class Aserver { public static void main(String arg ...

  6. 04747_Java语言程序设计(一)_第10章_网络与数据库编程基础

    例10.1说明InetAddress类的用法的应用程序. public class Example10_1 { public static void main(String args[]) { try ...

  7. 04747_Java语言程序设计(一)_第9章_输入和输出流

    例9.1一个文件复制应用程序,将某个文件的内容全部复制到另一个文件. import java.io.*; public class Example9_1 { public static void ma ...

  8. 04747_Java语言程序设计(一)_第7章_图形、图像与多媒体

    例7.1小应用程序用6种字型显示字符串,显示内容说明本身的字型. import java.applet.*; import java.awt.*; public class Example7_1 ex ...

  9. 04747_Java语言程序设计(一)_第6章_图形界面设计(二)

    例6.1声明一个面板子类,面板子类对象有3个选择框. class Panel1 extends JPanel { JCheckBox box1, box2, box3; Panel1() { box1 ...

随机推荐

  1. 好多邮箱的SMTP设置

    http://731771490.diandian.com/post/2011-04-20/19576550

  2. WPF 控件之ComboBox绑定[2]

    最近感觉新的方法Binding comboBox用起来很好用. 记录一下: <ComboBox Grid.Row=" x:Name="cboFamilyName" ...

  3. 【CSS3】横屏引导小动画

    演示地址:http://codepen.io/anon/pen/oXbXdX 主要知识点: @media all and (orientation : landscape) { /* 这是匹配横屏的状 ...

  4. Enabling Active Directory Authentication for VMWare Server running on Linux《转载》

    Enabling Active Directory Authentication for VMWare Server running on Linux Version 0.2 - Adam Breid ...

  5. 新建的硬盘-mount

    一.查看已经格式化或已挂接硬盘 df -aT 等命令(自己度娘) 二.查看未挂硬盘和未格式化硬盘 1.fdisk -l 比如/dev/sdb  如果已经分区,会有sdb1. 2.格式化 #mkfs - ...

  6. WebApi2官网学习记录---BSON

    BSON 是轻量级的,能够进行快速查询和高效的解码/编码.BSON方便查询是由于elements的前面都有一个表示长度的字段,所以解释器可以快速跳过这个elements:高效的解码/编码是因为nume ...

  7. SQL Server -ISNULL()函数

    SQL中有多种多样的函数,下面将为您介绍SQL中的ISNULL函数,包括其语法.注释.返回类型等,供您参考,希望对您学习SQL能够有所帮助. ISNULL 使用指定的替换值替换 NULL. 语法ISN ...

  8. sharding的基本思想和理论上的切分策略

    本文着重介绍sharding的基本思想和理论上的切分策略,关于更加细致的实施策略和参考事例请参考我的另一篇博文:数据库分库分表(sharding)系列(一) 拆分实施策略和示例演示 一.基本思想 Sh ...

  9. iPhoneKeyboard

    iPhoneKeyboard.Open static function Open (text : string, keyboardType : iPhoneKeyboardType = iPhoneK ...

  10. Cocos2d-x 3.x部署到安卓

    一.前期准备 下载下列软件: Python2.7 (https://www.python.org/downloads/) Cocos2d-x 3.x (http://www.cocos2d-x.org ...