例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. 无Root抓包:Packet Capture 1.2.3

    无Root抓包:Packet Capture 1.2.3 http://www.coolapk.com/apk/app.greyshirts.sslcapture

  2. 利用dedecms给近三天(或当天)发布的文章显示红色日期或加上new字或new小图片

    1)红色日期 <br>[field:pubdate runphp='yes'] <br>$a="<font color=red>".strfti ...

  3. Android BLE开发之Android手机与BLE终端通信

    本文来自http://blog.csdn.net/hellogv/ ,引用必须注明出处! 近期穿戴设备发展得非常火.把相关技术也带旺了,当中一项是BLE(Bluetooth Low Energy).B ...

  4. C# 大小写转换

    全部大写: string upper = str.ToUpper() 全部小写: string lower = str.ToLower(); str是需要转换的字符.

  5. repeater截取字数

    <%# Eval("ArticleName").ToString().Length > 14 ? Eval("ArticleName").ToStr ...

  6. Struts2.3.16.3 基本9个jar包

    实践证明,Struts2.3.16.3 至少要下面9个Jar包才能正常启动. commons-fileupload-1.3.1.jar commons-logging-1.1.3.jar freema ...

  7. 费马小定理&欧拉定理

    在p是素数的情况下,对任意整数x都有xp≡x(mod p).这个定理被称作费马小定理其中如果x无法被p整除,我们有xp-1≡1(mod p).利用这条性质,在p是素数的情况下,就很容易求出一个数的逆元 ...

  8. 慕课linux学习笔记(八)常用命令(5)

    解压缩命令 常用压缩格式 .zip .gz .bz2 .tar.gz .tar.bz2 zip [压缩文件名] [ 原文件 ] #压缩文件 -r [压缩文件名] [ 源目录] #压缩目录 -r [压缩 ...

  9. 简单的thinkPHP3.2运行实例。

    在上一篇的环境基础下. 我们用zendstudio12.5版本编写我们的代码.具体的下载方式在这里就不多做注明了.自己百度就可以搞定. 首先我们用zendstudio12.5 导入我们从网上随处都可以 ...

  10. python安装——Windows平台

    刚刚申请博客,第一次写随笔,记录下自己最近的学习情况,希望自己能够不断的学习,不断的丰富自己~ 最近刚开始学python,记录一下,希望大家相互学习,批评指正~ 1.下载python:https:// ...