04747_Java语言程序设计(一)_第8章_多线程
例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章_多线程的更多相关文章
- ArcGIS for Desktop入门教程_第七章_使用ArcGIS进行空间分析 - ArcGIS知乎-新一代ArcGIS问答社区
原文:ArcGIS for Desktop入门教程_第七章_使用ArcGIS进行空间分析 - ArcGIS知乎-新一代ArcGIS问答社区 1 使用ArcGIS进行空间分析 1.1 GIS分析基础 G ...
- ArcGIS for Desktop入门教程_第六章_用ArcMap制作地图 - ArcGIS知乎-新一代ArcGIS问答社区
原文:ArcGIS for Desktop入门教程_第六章_用ArcMap制作地图 - ArcGIS知乎-新一代ArcGIS问答社区 1 用ArcMap制作地图 作为ArcGIS for Deskto ...
- ArcGIS for Desktop入门教程_第四章_入门案例分析 - ArcGIS知乎-新一代ArcGIS问答社区
原文:ArcGIS for Desktop入门教程_第四章_入门案例分析 - ArcGIS知乎-新一代ArcGIS问答社区 1 入门案例分析 在第一章里,我们已经对ArcGIS系列软件的体系结构有了一 ...
- 04747_Java语言程序设计(一)_第3章_面向对象编程基础
链式编程 每次调用方法后,返回的是一个对象 /* * 链式编程 * 每次调用方法后,返回的是一个对象 */ class Student { public void study() { System.o ...
- 04747_Java语言程序设计(一)_第1章_Java语言基础
二进制0b开头 八进制0开头 十六进制0x开头 package com.jacky; public class Aserver { public static void main(String arg ...
- 04747_Java语言程序设计(一)_第10章_网络与数据库编程基础
例10.1说明InetAddress类的用法的应用程序. public class Example10_1 { public static void main(String args[]) { try ...
- 04747_Java语言程序设计(一)_第9章_输入和输出流
例9.1一个文件复制应用程序,将某个文件的内容全部复制到另一个文件. import java.io.*; public class Example9_1 { public static void ma ...
- 04747_Java语言程序设计(一)_第7章_图形、图像与多媒体
例7.1小应用程序用6种字型显示字符串,显示内容说明本身的字型. import java.applet.*; import java.awt.*; public class Example7_1 ex ...
- 04747_Java语言程序设计(一)_第6章_图形界面设计(二)
例6.1声明一个面板子类,面板子类对象有3个选择框. class Panel1 extends JPanel { JCheckBox box1, box2, box3; Panel1() { box1 ...
随机推荐
- <s:iterator> 序号
<s:iterator />的序号,解决这个问题有两种办法. 方法一:通过set标签实现: <s:set name="a" value=1/> <s: ...
- c语言 (linux下)
生成二进制 : gcc -o hello hello.c 生成汇编:gcc -o hello.s -S hello.c 生成预编译文件:gcc -o hello.i -E hello.c int ma ...
- openwrt上网配置的一些理解
其实已经有很多帖子讲过openwrt路由器上网配置了,我这里主要是讲我自己的一块硬件路由使用openwrt后的一些上网配置.之所以要研究我自己的配置,是因为硬件,硬件不一样,配置也就不一样,但是总的原 ...
- 用SNMP协议实现系统信息监控--CentOS
(1) 安装SNMP客户端以及服务端 安装内容为三项:net-snmp net-snmp-devel net-snmp-utils 安装命令:yum install net-snmp net- ...
- JavaScript 函数方法 - toString()
Function.prototype.toString() 返回函数代码的字符串形式. 描述 Function 对象覆盖了从 Object 继承来的 Object.prototype.toString ...
- Linq中的多表左联,详细语句
from m in context.WX_MemberCollectDish join d in context.Dish on m.DishID equals d.DishID into temp ...
- WndProc函数(转)
WndProc函数作用: 主要用在拦截并处理系统消息和自定义消息 比如:windows程序会产生很多消息,比如你单击鼠标,移动窗口都会产生消息.这个函数就是默认的消息处理函数.你可以重载这个函数来制定 ...
- 作为java应届生,面试求职那点事
找工作两星期多了.心情不爽,写点记录打发时间. 嘘~~自己的破事: 刚毕业,也过了实习,本理所应当的留在公司转正.可是为了谈了两年的女朋友回家见面.一切都顺利进行,妈妈也开心给了一万见面礼,一切都以 ...
- C#调用进程
Process process = new Process(); process.StartInfo.FileName = "123.exe"; process.StartInfo ...
- 简单数据结构———AVL树
C - 万恶的二叉树 Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:32768KB 64b ...