例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. Windows系统结构

    四种用户模式进程:1.系统支持进程,比如登录进程和会话管理器,并不是Windows服务,不有服务控制管理器启动2.服务进程,一些以Windows服务方式来运行的组件3.用户应用进程4.环境子系统服务器 ...

  2. Java中判断集合类为空的方法

    *****需要引入Spring的核心Jar包***** 工具类: org.springframework.util.CollectionUtils 方法: public static boolean ...

  3. vuex 模块

    今天,在我编写系统中一个模块功能的时候,由于我使用vuex存储数据的状态,并分模块存储.我是这样在存储文件中定义state,getters,actions,mutations的,我打算在不同模块文件都 ...

  4. ASIHttpRequest:创建队列、下载请求、断点续传、解压缩

    ps:本文转载自网络:http://ryan.easymorse.com/?p=12 感谢作者 工程完整代码下载地址:RequestTestDownload1 可完成: 下载指定链接的zip压缩文件 ...

  5. DOS命令大全--具体解释

    在Linux和Windows下都能够用nslookup命令来查询域名的解析结果 DOS命令大全一)MD--建立子文件夹 1.功能:创建新的子文件夹 2.类型:内部命令 3.格式:MD[盘符:][路径名 ...

  6. rsync+sersync实现数据文件实时同步

    一.简介 sersync是基于Inotify开发的,类似于Inotify-tools的工具: sersync可以记录下被监听目录中发生变化的(包括增加.删除.修改)具体某一个文件或某一个目录的名字: ...

  7. 私人C#笔记

      coust 定义常量 string是密封类,所以不能继承它 namespace默认是按照文件夹的结构命名的,如(System.文件夹.子文件夹),而且namespace是可以手动改的   Arra ...

  8. Asp.net中具体的日期格式化用法

    1.绑定时格式化日期方法: <ASP:BOUNDCOLUMN DATAFIELD= "JoinTime " DATAFORMATSTRING= "{0:yyyy-M ...

  9. ComboBox绑定数据源时触发SelectedIndexChanged事件的处理办法

    转载:http://blog.sina.com.cn/s/blog_629e606f01014d4b.html ComboBox最经常使用的事件就是SelectedIndexChanged.但在将Co ...

  10. 关于Ajax的技术组成与核心原理

    1.Ajax 特点: 局部刷新.提高用户的体验度,数据从服务器商加载 2.AJax的技术组成 不是新技术,而是之前技术的整合 Ajax: Asynchronous Javascript And Xml ...