Java必做实验4线程应用
admin
2024-02-08 18:17:09
0

(1). 运行以下三个程序(要求每个程序运行10次),并对输出结果给出分析。在报告中附上程序截图和详细的文字说明。(15分)

程序1:

package first;
//The Task for printing a character a specified number of times
class PrintChar implements Runnable{private char charToPrint;//The character to printprivate int times;//The number of times to repeatpublic PrintChar(char c,int t){charToPrint=c;times=t;}@Override/*Override the run()method to tell the system*what task to perform*/public void run(){for(int i=0;i

该程序是线程异步功能是的输出100个a,100个b和100个数字(1~100)

程序2:

该程序与上一题不同的是运用了线程池,用newFixedThreadPool创建了一个线程数为3的线程池,然后将和第一个程序相同的三个线程任务放进线程池,但运行时仍然是线程异步。

代码如下:

package first_2;import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;//The Task for printing a character a specified number of times
class PrintChar implements Runnable{private char charToPrint;//The character to printprivate int times;//The number of times to repeatpublic PrintChar(char c,int t){charToPrint=c;times=t;}@Override/*Override the run()method to tell the system*what task to perform*/public void run(){for(int i=0;i

可见仍无规律可循,说明线程池的多线程是线程异步的。

package first_3;
import java.util.concurrent.*;
public class AccountWithoutDSync {private static Account account = new Account();public static void main(String args[]) {ExecutorService executor = Executors.newCachedThreadPool();//Creat and launch 100 threadsfor (int i = 0; i < 100; i++) {executor.execute(new AddAPennyTask());}executor.shutdown();//Wait until all tasks are finishedwhile (!executor.isTerminated()) {}System.out.println("What is balance? " + account.getBalance());}//A thread for adding a penny to the accountprivate static class AddAPennyTask implements Runnable {public void run() {account.deposit(1);}}//An inner class for accountprivate static class Account {private int balance = 0;public int getBalance() {return balance;}public void deposit(int amount) {int newBalance = balance + amount;//This delay is deliberately added to magnify the//data-corruption problem and make it easy to see.try {Thread.sleep(5);} catch (InterruptedException ex) {}balance = newBalance;}}
}

程序3: 

package first_3;
import java.util.concurrent.*;
public class AccountWithoutDSync {private static Account account = new Account();public static void main(String args[]) {ExecutorService executor = Executors.newCachedThreadPool();//Creat and launch 100 threadsfor (int i = 0; i < 100; i++) {executor.execute(new AddAPennyTask());}executor.shutdown();//Wait until all tasks are finishedwhile (!executor.isTerminated()) {}System.out.println("What is balance? " + account.getBalance());}//A thread for adding a penny to the accountprivate static class AddAPennyTask implements Runnable {public void run() {account.deposit(1);}}//An inner class for accountprivate static class Account {private int balance = 0;public int getBalance() {return balance;}public void deposit(int amount) {int newBalance = balance + amount;//This delay is deliberately added to magnify the//data-corruption problem and make it easy to see.try {Thread.sleep(5);} catch (InterruptedException ex) {}balance = newBalance;}}
}

(2). 编写Java应用程序实现如下功能:第一个线程输出数字1,2,..,12,第二个线程输出英文单词数字和月份One January, Two February, …, Twelve December,输出的顺序和格式为1OneJanuary2TwoFebruary...12TwelveDecember,即每1个数字紧跟着2个英文单词的方式。要求线程间实现通信。要求采用实现Runnable接口和Thread类的构造方法的方式创建线程,而不是通过Thread类的子类的方式。在报告中附上程序截图、运行结果截图和详细的文字说明。(15分)

这题最主要的还是线程之间的通信,在每个线程

输出相应的数字或字符后,在下一个输出前,都要判断是否要wait,才能保证相互的连续性

源代码如下:

首先是实现两者通信的类(单独开了一个包):

其中定义了两个线程的进度timeOf...;然后先定义了一个String类型的数组month来使后面输出方便,再就是分别定义了synchronized 下的printNumber和printChatrs方法来使两线程同时进行两着主语句相差不大,printChars下定义了一个index来记录访问month的下标,注意一下两线程的输出顺序(再if里面注意判断)。

package second;
public class Connect {int timesOfInt = 1;int timesOfString = 1;String []month = {"One January", "Two  February", "Three March", "Four April", "Five May","Six June", "Seven July", "Eight August", "Nine September", "Ten October", "Eleven November", "Twelve December"};//先定义一下月份,方便输出synchronized void printNumber() {//线程1实现的输出1到12for (timesOfInt = 1; timesOfInt <= 12; timesOfInt++) {if (timesOfInt > timesOfString) //对应的字母未输出{try {wait();}catch (InterruptedException ex) {}}System.out.print(timesOfInt);notify();//输出后唤醒另一个线程}}synchronized void printChars() {//线程2输出One January到Twelve Decemberint index = 0;//记录month的下标for (timesOfString = 1; timesOfString <= 12; timesOfString++) {if (timesOfInt <= timesOfString) {//相应数字未输出try {wait();}catch (InterruptedException ex) {}}System.out.print(month[index++]+" ");//加个空格输出美观点notify();//唤醒另一个线程}}
}

然后在主运行的类下定义了两个方法printInt和printString均继承了Runnable接口,通过它们来调用非静态Connect中的方法,main类大体就只是调用:

package second;
class printInt implements  Runnable{Connect connect;//创建了connect类实例为了调用非static方法printInt (Connect connect1){connect=connect1;}public void run(){connect.printNumber();}//实现Ruunable接口
}
class printString implements Runnable{Connect connect;//创建了connect类实例为了调用非static方法printString(Connect connect1){connect=connect1;}public void run(){connect.printChars();}//实现Ruunable接口
}
public class second{    public static void main(String args[]){Connect connect=new Connect();//同一connect创建线程确保通信Thread threadA=new Thread(new printInt(connect));//Thread方法实现接口Thread threadB=new Thread(new printString(connect));threadA.start();threadB.start();}
}

(3). 编写Java应用程序实现如下功能:创建工作线程,模拟银行现金账户取款操作。多个线程同时执行取款操作时,如果不使用同步处理,会造成账户余额混乱,要求使用syncrhonized关键字同步代码块,以保证多个线程同时执行取款操作时,银行现金账户取款的有效和一致。要求采用实现Runnable接口和Thread类的构造方法的方式创建线程,而不是通过Thread类的子类的方式。在报告中附上程序截图、运行结果截图和详细的文字说明。(25分)

这道题很明显用syncrhonized的目的是,存钱时使得这次存款对应的输出余额相对应,不要让同时存的另一个数额也加进这次的余额计算中,所以采用syncrhonized关键字实现

源代码如下:

package third;
import java.util.*;
class Account implements  Runnable{private double account;//账户总额private String name;//账户名public double outAccount;//取款Account(double money,String s){account=money;name=s;}void setOutAccount(){System.out.print("请输入要取款的金额:");Scanner scanner=new Scanner(System.in);outAccount=scanner.nextDouble();}public synchronized void run(){setOutAccount();//outAccount记录这次要取的数目if(account

注意删去Account下的run的synchronized也执行一次,发现第二次要求先输入所有取款金额而不删时不用。

(4). 有一座东西向的桥,只能容纳一个人,桥的东边有20个人(记为E1,E2,…,E20)和桥的西边有20个人(记为W1,W2,…,W20),编写Java应用程序让这些人到达对岸,每个人用一个线程表示,桥为共享资源,在过桥的过程中输出谁正在过桥(不同人之间用逗号隔开)。运行10次,分别统计东边和西边的20人先到达对岸的次数。要求采用实现Runnable接口和Thread类的构造方法的方式创建线程,而不是通过Thread类的子类的方式。在报告中附上程序截图、运行结果截图和详细的文字说明。(25分)

这题和第一题2有点类似的样子,所以直接套过来用了。

源代码:

东边的人定义,变量有名字name第几个人num(用num+1表示),方法setEast实现了对East类的初始化,随后就是对run的实现.

西边的人的定义与东边基本一样,名字啥的修改一下就好了。

package four;
class East implements Runnable{private String name;//过桥人的名字private int num;//记录第num+1个人过桥(因为num当输出了)public void setEast(int num){//初始化我搞这了String s=Integer.toString(num);name="E"+s;this.num=num;}public void run(){//实现RunnableSystem.out.println(name+"正在过桥......");//输出过桥者的信息if(num==19)System.out.println("东边的人全部过桥啦!");//最后一人过桥则输出提}
}
class West implements Runnable{//与East类似的定义private String name;private int num;public void setWest(int num){//过桥者String s=Integer.toString(num);name="W"+s;this.num=num;}public void run(){System.out.println(name+"正在过桥......");//输出过桥者的信息if(num==19)//最后一人过桥则输出提示System.out.println("西边的人全部过桥啦!");}
}
public class Bridge {public static void main(String []args){for(int i=0;i<10;i++){int count=0;East []east=new East[20];West []west=new West[20];//定义桥的东西边各20个人Thread []threadWest=new Thread[20];Thread []threadEest=new Thread[20];//定义两边的线程for(int j=0;j<20;j++){east[j]=new East();east[j].setEast(j);threadEest[j]=new Thread();threadEest[j]=new Thread(east[j]);west[j]=new West();west[j].setWest(j);threadWest[j]=new Thread();threadWest[j]=new Thread(west[j]);//初始化}for(int j=0;j<20;j++){threadWest[j].start();threadEest[j].start();//开始}System.out.println("第"+(i+1)+"一波结束啦!");System.out.println("******分割******");}}
}

main主要实现了10次循环计数,以及对20个类和线程的初始化,然后就是计算东西

先到达对岸的次数(太菜了只会看着答案人工计算)qwq。

相关内容

热门资讯

不良率上升倒逼防线前移 银行收... 银行正在给个人信贷风控“上强度”。上海证券报记者近期自业内多方了解到,不少银行零售信贷业务从审批权限...
自媒体新手如何快速涨粉?这5个... 自媒体新手如何快速涨粉?这5个技巧让你少走弯路! 嗨,我是小融。 最近很多刚入门自媒体的朋友问我,怎...
乌兰察布市财政局关于黄金领域非... 乌兰察布市财政局关于黄金领域 非法金融活动风险提示 近期,黄金价格波动频繁,市场热度持续攀升,各类假...
一只鸡蛋架“直发”俄罗斯 无锡... (来源:无锡新传媒) 转自:无锡新传媒 一只3D打印塑料鸡蛋架,成为无锡国际邮件互换局正式开通运营后...
武汉楼市开启红五月 新房成交量... 原标题:武汉楼市开启红五月 数据爆表,新房成交量较去年同期翻番 武汉城建未来中心项目营销中心现场来...
一家精神病院竟现身A股公司前十... 5月8日,有投资者发现,盛通股份前十大股东名单中,竟出现了一家精神病院的身影。这家精神病院全称为“上...
真的老了!哈登心魔难除 骑士还... 哈登又拉胯了。 刚刚过去的两场东部半决赛,骑士都输的相当狼狈,而哈登的发挥更是灾难级的。 半决赛G1...
精神病院通报成上市公司前十大股... 近日,上市公司盛通股份发布一季报,披露了前十大股东名单。其中,一家名为“上饶市广丰区十五岭山精神病医...
天溯计量发布年报 上市首年检测... 转自:中国经营网 文 近日,计量检测机构天溯计量(301449.SZ)发布了2025年年度报告。年...
原创 全... 美伊真要停火了? 一页纸协议让全球油价闪崩! 就在今天,全球市场被一条消息炸开了锅。美国白宫觉得,他...
百信银行业绩:26Q1净利润大... 4月底,中信百信银行股份有限公司(下称“百信银行”)2025年财报及2026年一季度报接连披露—— ...
美光科技股价单周飙升38% 市... 【CNMO科技消息】受全球内存芯片短缺影响,美光科技股价本周大幅上涨。截至周五收盘,美光股价报746...
江西一精神病院炒股,炒成上市公... 近日,上市公司盛通股份(002599.SZ)发布一季报,披露了前十大股东名单,其中一家名为“上饶市广...
专访中国太保副总裁俞斌:从“+... 拥抱AI(人工智能),不再是保险行业的“选择题”,而是关乎企业生存与发展的“必答题”,更是企业决胜未...
多平台优化算法:美团取消超时扣... 图片来源:界面图库 5月8日,网信中国发布消息称,生活服务类平台算法治理已取得初步成效,美团、淘宝、...
原创 2... 2025年,国内系统重要性银行名单正式公布。这是我国金融体系的核心支柱,一共21家银行入选,它们是维...
东海县供销总社:“供销+龙头企... 近日,东海县供销合作总社鼎味泰直营店正式开业。作为东海县供销系统打造的新型社企便民服务网点,该门店的...
原创 阿... 深夜,一家零食店铺的客服后台弹出一条消息:“我上次买的芒果干,这次想换个不那么酸的口味,再帮我推荐几...
和平湾全新项目前瞻 负公摊、唯... 在沈阳,如果想在主城核心区域找一块容积率低于1.5的住宅用地,难度有多大? 过去三年,沈阳主城核心区...
精神病院与国际投行高盛同在 盛... 近日,盛通股份(002599.SZ)发布一季报,其前十大股东名单中,第九位为“上饶市广丰区十五岭山精...