导航:首页 > 编程语言 > java多线程习题

java多线程习题

发布时间:2025-08-05 01:13:45

‘壹’ 基础java题 试编写一个多线程的程序:启动4个线程。其中两个循环10次,每次将某全局变量加1,另两个循环1

publicclassDay18_A{
publicstaticvoidmain(String[]args)throwsInterruptedException{
Recounrec=Recoun.getRec();
Thread[]trr=newThread[4];
for(inti=0;i<4;i++){
trr[i]=newThread(newNumberTest(rec,i),"线程"+(i+1)+": ");
}
for(Threadthread:trr){
thread.start();
}
for(Threadthread:trr){
thread.join();
}
System.out.println("所有线程结束查看结果:"+rec.getCount());
}
}

{
privateRecounre;
privateintn;
NumberTest(Recounr,inti){
this.re=r;
this.n=i;
}
publicvoidrun(){
for(inti=0;i<10;i++){
re.method(n);
}
}
}
classRecoun{
privateintcount=0;
privateRecoun(){
}
privatestaticfinalRecounrec=newRecoun();
publicstaticRecoungetRec(){
returnrec;
}
publicsynchronizedvoidmethod(inti){
if(i%2==0){
System.out.println(Thread.currentThread().getName()+(count++));
}else{
System.out.println(Thread.currentThread().getName()+(count--));
}
}
publicsynchronizedintgetCount(){
returncount;
}
}

‘贰’ 课程设计题目,多线程编程:医院门诊模拟,想用java实现,求大神指点

典型的生产者消费者模型。

了解j5的并发库,那个并发库中有适合组件实现。

如果不了解,这么来:

创建一个队列,此队列要求线程安全,如果队列为空则消费者阻塞。如果队列达到某个最大值,则阻塞生产者。

队列用,普通的list或实现好的队列包装成线程安全的。

用synchronized同步原方法或代码块。

写一个或n个线程,模拟病人,排队办理业务,往上面的队列中添加数据。

当达到队列的最大容积,阻塞,等待生产者线程取数据。

阻塞:makerLock.wait();//虚拟机会出让线程挂起,其实就是操作系统,保存当前线程在cpu上的运行状态。再出让线程正在使用的cpu资源,占用的内存不会释放。

往队列插入数据的时候,因为不知道是否有消费者处于等待状态,通知消费者:

customerLock.notifyAll();//虚拟机调度消费者线程运行,实际上是操作系统,把保存的消费者线程状态,从新加载到cpu中接着运行。接着运行线程是任意的,取决于不同操作系统的线程调度算法

消费者线程读取一个数据后,要通知生产者,可以继续,道理同上:

makerLock.notifyAll();

队列中,无数据可读的时候:

customerLock.wait();//原理同上,

最后注意,生产者跟消费者使用了两个不同的对象锁。lock.wait()的使用方法是这样的:

synchronized(lock){

......

while(condition==true){

lock.wait();

}

......

Objecto=queen.pop();

lock.notifyAll();

}

最后启动n个线程读队列,模拟办理业务的窗口;n个线程写队列,模拟病人排队。

新线程库也有跟老线程库对应的方法,新线程库有线程安全的高效队列。没有上面麻烦,但上面写的是理解新线程数据结构与实现的基础。

packagecom.;

importjava.util.LinkedList;
importjava.util.List;
importjava.util.Random;

publicclassTestThread2{

//缓冲上限
privatelongbufsize;

//缓冲
privateList<String>buf;

publicTestThread2(){
bufsize=5;
buf=newLinkedList<String>();
}

//生产者调用
publicvoidput(Strings){
//模拟生产者跟不上消费者
/*
try{
Thread.sleep(100);
}catch(InterruptedExceptione){
}
*/

synchronized(this){
//超过队列限制就等待
while(buf.size()==bufsize){
System.out.println("队列已满,生产者:"+Thread.currentThread().getId()+"开始等待。");
try{
this.wait();
}catch(InterruptedExceptione){
}
}

buf.add(s);

//通知消费者
this.notifyAll();
}

}

//消费者调用
synchronizedpublicStringtake(){

//模拟消费者跟不上生产者
try{
Thread.sleep(100);
}catch(InterruptedExceptione){
}

Strings=null;

synchronized(this){
while(buf.size()==0){
System.out.println("队列为空,消费者:"+Thread.currentThread().getId()+"开始等待。");
try{
this.wait();
}catch(InterruptedExceptione){
}
}

//取先放入的元素,并移除
s=buf.get(0);
buf.remove(0);

//通知生产者
this.notifyAll();
}

returns;
}

publicstaticvoidmain(String[]args){
//自己实现的,安全队列
finalTestThread2tt=newTestThread2();

//生产者
Threadp=newThread(newRunnable(){

@Override
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
Randomr=newRandom();
tt.put(String.valueOf(r.nextInt(10)));
}
}

});

//消费者
Threadc1=newThread(newRunnable(){

@Override
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
System.out.println("线程:"+Thread.currentThread().getId()+"获取到数据"+tt.take());
}
}

});

Threadc2=newThread(newRunnable(){

@Override
publicvoidrun(){
while(!Thread.currentThread().isInterrupted()){
System.out.println("线程:"+Thread.currentThread().getId()+"获取到数据"+tt.take());
}
}

});

p.start();
c1.start();
c2.start();

try{
p.join();
c1.join();
c2.join();
}catch(InterruptedExceptione){
}


}

}

‘叁’ java 用多线程模拟龟兔赛跑:

public class TortoiseAndHareRace {
public static void main(String[] args) {
Runnable vs=new Race();
Thread hare=new Thread(vs,"Hare");
Thread tortoise =new Thread(vs,"Tortoise");
System.out.println("Ready!GO!");
hare.start();
tortoise.start();
}
}
class Race implements Runnable{
private static final int S=1000;
@Override
public void run() {
if(Thread.currentThread().getName().equals("Hare")){
int sHare=0;
while(sHare<=S){
sHare+=5;
if(sHare%20==0)
try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
}
}else{
int sTortoise=0;
while(sTortoise<=S){
sTortoise++;
if(sTortoise%100==0)
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

‘肆’ Java的龟兔赛跑多线程问题

publicclassCompetition{
=false;//用来标记是否有人到达终点,到达终点后游戏结束
//乌龟的实现方式
{
privatevolatileinttotal=0;//用来记录当前已经前行了多少距离
@Override
publicvoidrun(){
while(!gameOver){
intstep=(int)(Math.random()*5+1);//产生1-5的随机数
total+=step;
try{
Thread.sleep(200);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}

}
publicintgetTotal(){
returntotal;
}
}
//兔子的实现方式
{
privatevolatileinttotal=0;
@Override
publicvoidrun(){
while(!gameOver){
intstep=(int)(Math.random()*5+1);
total+=step;
try{
Thread.sleep(200);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}
publicintgetTotal(){
returntotal;
}

}
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
finalTortoisetortoise=newTortoise();
finalRabbitrabbit=newRabbit();
newThread(tortoise).start();
newThread(rabbit).start();
//下面多起了一个线程,相当于比赛的时候的裁判员,他每隔一段时间就看一下是否有人到达终点,若有人到达则宣判该人获胜,游戏结束
newThread(newRunnable(){

@Override
publicvoidrun(){
//TODOAuto-generatedmethodstub
while(!gameOver){
inttorLen=tortoise.getTotal();//获得乌龟前行的距离
intrabLen=rabbit.getTotal();//获得兔子前行的距离
System.out.println("乌龟:"+torLen+",兔子"+rabLen);
if(torLen>=100&&rabLen<100){
System.out.println("乌龟获胜!!!");
gameOver=true;
}elseif(rabLen>=100&&torLen<100){
System.out.println("兔子获胜!!!");
gameOver=true;
}elseif(rabLen>=100&&torLen>=100){//这里有可能两人同时到达终点
System.out.println("同时到达终点!!!");
gameOver=true;
}
try{
Thread.sleep(210);
}catch(InterruptedExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
}

}).start();

}

‘伍’ JAVA采用实现Runnable接口的多线程技术,用50个线程,生成10000个[1-1000]间的随机整数。

Java利用实现Runnable接口的多线程技术生成大量随机数,具体案例中,定义了一个名为RandomNumber的类,实现了Runnable接口,用于生成随机数。该类包含一个锁对象lock,用于同步处理,一个Random对象用于生成随机数,以及一个整数sum,用于记录生成的随机数总数。

RandomNumber类的构造函数初始化了锁对象和Random对象。其run方法实现多线程并发生成随机数,使用while循环,循环中首先生成一个0到1000之间的随机数。当生成的随机数等于0时,继续循环;否则,如果sum已经达到10000,则结束循环。

为了使程序运行效果更明显,run方法中加入了一个1毫秒的延时操作。接着,使用synchronized关键字确保在更新sum值时的线程安全,通过判断sum是否小于10000来决定是否继续生成随机数。当满足条件时,将sum值加1,并输出当前线程名和生成的随机数。

在main方法中,创建了一个RandomNumber实例,并启动50个线程,每个线程都执行RandomNumber的run方法,从而并发生成随机数。

这种多线程技术的应用,不仅能够提高程序的执行效率,还能帮助理解Java中线程同步的概念和实现方式。通过这种方式,每个线程都能独立地生成随机数,并通过锁对象确保了多线程环境下的数据一致性。

在实际开发中,这种技术常用于需要大量并发处理的任务,如网络请求、文件读写等场景,能够显着提升程序的处理能力和用户体验。

值得注意的是,虽然通过线程并发可以提高效率,但也需要关注线程之间的协调和资源竞争问题,避免产生死锁或资源竞争等并发编程中的常见问题。

阅读全文

与java多线程习题相关的资料

热点内容
androidmainxml 浏览:109
des可逆加密算法 浏览:249
aix查看系统信息常用命令 浏览:154
phpmemcache实例 浏览:249
爆枪源码 浏览:566
编程大佬能记住所有代码 浏览:858
如何批量注册国家反诈app 浏览:526
实现ping命令 浏览:19
cmd进入管理员命令 浏览:479
pdf在线编辑修改 浏览:967
文件夹是只读是什么意思 浏览:88
服务器如何知道访问域名 浏览:319
java网络编程实验总结 浏览:85
linux下dns服务器配置 浏览:707
我的命令是绝对的 浏览:932
助飞器app在哪里下 浏览:64
无广告win10解压缩 浏览:476
台湾的服务器怎么选云服务器 浏览:813
群晖媒体服务器平板上怎么看 浏览:625
pdf文件怎么转换成jpg格式 浏览:724