Java多线程综合案例

数字加减

设计4个线程对象,两个线程执行减操作,两个线程执行加操作

public class ThreadDemo{
    public static void main(String[] args) throws Exception {
        Resource res=new Resource();
        AddThread at=new AddThread(res);
        SubThread st=new SubThread(res);
        new Thread(at,"加法线程A:").start();
        new Thread(at,"加法线程B:").start();
        new Thread(st,"减法线程X:").start();
        new Thread(st,"减法线程Y:").start();
        
        
        
    }
}
class AddThread implements Runnable{//加法操作
    private Resource resource;
    public AddThread(Resource resource) {
        this.resource=resource;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int x=0;x<50;x  ) {
            try {
                this.resource.add();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
class SubThread implements Runnable{//减法操作
    private Resource resource;
    public SubThread(Resource resource) {
        this.resource=resource;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int x=0;x<50;x  ) {
            try {
                this.resource.sub();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
class Resource{//定义一个操作的资源
    private int num=0;//这个要进行加减操作的数据
    private boolean flag=true;//加减的切换
    //flag=true;表示可以进行加法操作,但无法进行减法操作
    //flag=false;表示可以进行减法操作,但是无法进行加法操作
    public synchronized void add() throws Exception {//执行加法操作
        if(this.flag==false) {//线程需要执行的是减法操作,加法操作要等待处理
            super.wait();
        }
        Thread.sleep(100);
        this.num  ;
        System.out.println("加法操作-" Thread.currentThread().getName() "num=" this.num);
        this.flag=false;//加法操作执行完毕,需要执行减法处理
        super.notifyAll();//唤醒全部等待处理
    }
    public synchronized void sub() throws Exception {//执行减法操作
        if(this.flag==true) {//线程需要执行的是加法操作,减法操作要等待处理
            super.wait();
        }
        Thread.sleep(200);
        this.num--;
        System.out.println("减法操作-" Thread.currentThread().getName() "num=" this.num);
        this.flag=true;//减法操作执行完毕,现在要执行加法操作
        super.notifyAll();//唤醒全部等待线程
    }
}

这一题目是经典的多线程开发操作,这个程序里面一定要考虑的核心本质在于:加一个、减一个,整体的计算结果应该只在0、-1、1之间循环出现

生产电脑

设计一个生产电脑和搬运电脑的类,要求生产一台电脑就搬走一台电脑,如果没有新电脑的生产就等待新电脑生产;如果生产出的电脑没有搬走,则要等待电脑搬走之后再生产,并统计出电脑生产的数量

解答:在本程序之中实现的就是一个标准的生产者与消费者的处理模型

public class ThreadDemo{
    public static void main(String[] args) throws Exception {
        
        Resource res=new Resource();
        new Thread(new Producer(res)).start();
        new Thread(new Consumer(res)).start();
        
    }
}
class Producer implements Runnable{
    private Resource resource;
    public Producer(Resource resource) {
        this.resource=resource;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int x=0;x<50;x  ) {
            
            this.resource.make();
        }
        
    }
    
}
class Consumer implements Runnable{
    private Resource resource;
    public Consumer(Resource resource) {
        this.resource=resource;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int x=0;x<50;x  ) {
    
            this.resource.get();
        }
        
    }
    
}
class Resource{
    private Computer computer;
    private boolean flag=true;
    public synchronized void make() {
        if(this.computer!=null) {//已经生产过了
            try {
                super.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.computer=new Computer("小米电脑",1.1);
        System.out.println("生产电脑" this.computer);
        super.notifyAll();
    }
    public synchronized void get() {
        if(this.computer==null) {//还没有生产
            try {
                super.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("取走电脑" this.computer);
        this.computer=null;//已经取走了
        super.notifyAll();
    }
}
class Computer{
    private static int count=0;//表示生产个数
    private String name;
    private double price;
    public Computer(String name,double price) {
        this.name=name;
        this.price=price;
        count  ;
    }
    public String toString(){
        return "第" count  "台电脑" "电脑名字:" this.name "、价值:" this.price;
    }
}

竞争抢答

实现一个竞拍抢答程序:要求设置三个抢答者(三个线程),而后发出抢答指令,抢答成功给出抢答成功提示,抢答失败给出抢答失败提示

由于需要牵扯到数据的返回所以使用Callable更简单

package java线程;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class ThreadDemo{
	public static void main(String[] args) throws Exception {
		
		Mythread mt=new Mythread();
		FutureTask<String> taskA=new FutureTask<String>(mt);
		FutureTask<String> taskB=new FutureTask<String>(mt);
		FutureTask<String> taskC=new FutureTask<String>(mt);
		new Thread(taskA,"竞赛者A").start();
		new Thread(taskB,"竞赛者B").start();
		new Thread(taskC,"竞赛者C").start();
		System.out.println(taskA.get());
		System.out.println(taskB.get());
		System.out.println(taskC.get());
		
	}
}
class Mythread implements Callable<String>{
	private boolean flag=false;

	@Override
	public String call() throws Exception {
		// TODO Auto-generated method stub
		synchronized (this) {
			if(this.flag==false) {
				this.flag=true;
				return Thread.currentThread().getName() "抢答成功";
			}
			else {
				return Thread.currentThread().getName() "抢答失败";
			}
			
		}
	}
	
}

使用Callable的主要原因是因为Callable拥有返回值方便我们处理

到此这篇关于Java多线程编程综合案例详解的文章就介绍到这了,更多相关Java多线程编程内容请搜索Devmax以前的文章或继续浏览下面的相关文章希望大家以后多多支持Devmax!

Java多线程编程综合案例详解的更多相关文章

  1. iOS:核心图像和多线程应用程序

    我试图以最有效的方式运行一些核心图像过滤器.试图避免内存警告和崩溃,这是我在渲染大图像时得到的.我正在看Apple的核心图像编程指南.关于多线程,它说:“每个线程必须创建自己的CIFilter对象.否则,你的应用程序可能会出现意外行为.”这是什么意思?我实际上是试图在后台线程上运行我的过滤器,所以我可以在主线程上运行HUD(见下文).这在coreImage的上下文中是否有意义?

  2. ios – 意外的核心数据多线程违规

    我正在使用苹果的并发核心数据调试器.-com.apple.CoreData.ConcurrencyDebug1有时候我得到__Multithreading_Violation_AllThatIsLeftToUsIsHonor__,即使我几乎肯定线程没有被违反.这是发生异常的代码的一部分(代码是扩展NSManagedobject的协议的一部分):代码在上下文的执行:块中执行.这里是线程信息:和调试器

  3. ios – UIGraphicsBeginImageContextWithOptions和多线程

    我对UIGraphicsBeginImageContextWithOptions和线程有点困惑,因为根据UIKitFunctionReferenceUIGraphicsBeginImageContextWithOptions应该只在主线程上调用.当被调用时,它创建一个基于位图的上下文,可以使用CoreGraphics的函数或者像-drawInRect这样的方法来处理:对于UIImage,-draw

  4. Swift之dispatch_source实现多线程定时关闭功能

    由于在项目中需要用到定时关闭音频功能,本来打算用NSTimer的,可是写起来并不是那么精简好用,所以又在网上找到相关的实例,结合自己项目需要,就写出了如下代码,还请大家指教,废话不多说:

  5. swift 多线程实现

  6. swift_多线程基础_最简单用法GCD, NSOperationQueue, NSThread

    ////ViewController.swift//study1-1//Createdbyadminon15/12/28.//copyright2015年admin.Allrightsreserved.//importUIKitclassViewController:UIViewController{@IBOutletvarmyLable:UILabel?@IBActionfuncclickBut

  7. swift__多线程GCD详解

    有以下*-disPATCH_QUEUE_PRIORITY_HIGH:*-disPATCH_QUEUE_PRIORITY_DEFAULT:多用默认*-disPATCH_QUEUE_PRIORITY_LOW:*-disPATCH_QUEUE_PRIORITY_BACKGROUND:*第二个参数为预留参数,一般为0*/letmyQueue:dispatch_queue_t=dispatch_get_global_queue//用异步的方式运行队列里的任务dispatch_async//-------------

  8. Swift - 多线程实现方式3 - Grand Central DispatchGCD

    dispatchqueue可以是并发的或串行的。dispatch_suspend后,追加到DispatchQueue中尚未执行的任务在此之后停止执行。6//创建并行队列conQueue:dispatch_queue_t=dispatch_queue_create//暂停一个队列dispatch_suspend//继续队列dispatch_resume6,dispatch_once一次执行保证dispatch_once中的代码块在应用程序里面只执行一次,无论是不是多线程。注意,我们不能(直接)取消我们已经提

  9. 【Swift】三种多线程处理方式

    )Threadbtn.frame=CGRectMakeThreadbtn.setTitle//普通状态下的文字Threadbtn.setTitle//触摸状态下的文字letmethod:Selector=methodarr[index!]Threadbtn.addTargetself.view.addSubview;}}overridefuncdidReceiveMemoryWarning(){super.didReceiveMemoryWarning()}//1.NSThread线程functestNS

  10. Swift多线程之GCD

    学自:http://www.jianshu.com/p/2598a4e9c139

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部