亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java多線程編程綜合案例詳解

 更新時間:2022年07月26日 14:05:08   作者:樣子的木偶  
這篇文章將通過三個案例帶大家了解一下Java中的多線程編程,文中的示例代碼介紹詳細,對我們的學習或工作有一定的價值,感興趣的小伙伴可以了解一下

Java多線程綜合案例

數(shù)字加減

設計4個線程對象,兩個線程執(zhí)行減操作,兩個線程執(zhí)行加操作

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;//這個要進行加減操作的數(shù)據(jù)
    private boolean flag=true;//加減的切換
    //flag=true;表示可以進行加法操作,但無法進行減法操作
    //flag=false;表示可以進行減法操作,但是無法進行加法操作
    public synchronized void add() throws Exception {//執(zhí)行加法操作
        if(this.flag==false) {//線程需要執(zhí)行的是減法操作,加法操作要等待處理
            super.wait();
        }
        Thread.sleep(100);
        this.num++;
        System.out.println("加法操作-"+Thread.currentThread().getName()+"num="+this.num);
        this.flag=false;//加法操作執(zhí)行完畢,需要執(zhí)行減法處理
        super.notifyAll();//喚醒全部等待處理
    }
    public synchronized void sub() throws Exception {//執(zhí)行減法操作
        if(this.flag==true) {//線程需要執(zhí)行的是加法操作,減法操作要等待處理
            super.wait();
        }
        Thread.sleep(200);
        this.num--;
        System.out.println("減法操作-"+Thread.currentThread().getName()+"num="+this.num);
        this.flag=true;//減法操作執(zhí)行完畢,現(xiàn)在要執(zhí)行加法操作
        super.notifyAll();//喚醒全部等待線程
    }
}

這一題目是經(jīng)典的多線程開發(fā)操作,這個程序里面一定要考慮的核心本質(zhì)在于:加一個、減一個,整體的計算結(jié)果應該只在0、-1、1之間循環(huán)出現(xiàn)

生產(chǎn)電腦

設計一個生產(chǎn)電腦和搬運電腦的類,要求生產(chǎn)一臺電腦就搬走一臺電腦,如果沒有新電腦的生產(chǎn)就等待新電腦生產(chǎn);如果生產(chǎn)出的電腦沒有搬走,則要等待電腦搬走之后再生產(chǎn),并統(tǒng)計出電腦生產(chǎn)的數(shù)量

解答:在本程序之中實現(xiàn)的就是一個標準的生產(chǎn)者與消費者的處理模型

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) {//已經(jīng)生產(chǎn)過了
            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("生產(chǎn)電腦"+this.computer);
        super.notifyAll();
    }
    public synchronized void get() {
        if(this.computer==null) {//還沒有生產(chǎn)
            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;//已經(jīng)取走了
        super.notifyAll();
    }
}
class Computer{
    private static int count=0;//表示生產(chǎn)個數(shù)
    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;
    }
}

競爭搶答

實現(xiàn)一個競拍搶答程序:要求設置三個搶答者(三個線程),而后發(fā)出搶答指令,搶答成功給出搶答成功提示,搶答失敗給出搶答失敗提示

由于需要牽扯到數(shù)據(jù)的返回所以使用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多線程編程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • JMS簡介與ActiveMQ實戰(zhàn)代碼分享

    JMS簡介與ActiveMQ實戰(zhàn)代碼分享

    這篇文章主要介紹了JMS簡介與ActiveMQ實戰(zhàn)代碼分享,具有一定借鑒價值,需要的朋友可以參考下
    2017-12-12
  • Spring Cloud Gateway去掉url前綴

    Spring Cloud Gateway去掉url前綴

    這篇文章主要介紹了Spring Cloud Gateway去掉url前綴的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java之String類型的編碼方式轉(zhuǎn)換

    Java之String類型的編碼方式轉(zhuǎn)換

    這篇文章主要介紹了Java之String類型的編碼方式轉(zhuǎn)換,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • SpringBoot中實現(xiàn)訂單30分鐘自動取消的三種方案分享

    SpringBoot中實現(xiàn)訂單30分鐘自動取消的三種方案分享

    在電商和其他涉及到在線支付的應用中,通常需要實現(xiàn)一個功能:如果用戶在生成訂單后的一定時間內(nèi)未完成支付,系統(tǒng)將自動取消該訂單,本文將詳細介紹基于Spring Boot框架實現(xiàn)訂單30分鐘內(nèi)未支付自動取消的幾種方案,并提供實例代碼,需要的朋友可以參考下
    2023-10-10
  • Spring boot多線程配置方法

    Spring boot多線程配置方法

    這篇文章主要為大家詳細介紹了Spring boot多線程配置方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • Java并發(fā)編程中的ReentrantLock詳解

    Java并發(fā)編程中的ReentrantLock詳解

    這篇文章主要介紹了Java并發(fā)編程中的ReentrantLock詳解,從Java 5 開始,引入了一個高級的處理并發(fā)的java.util.concurrent包,它提供了大量更高級的并發(fā)功能,能大大簡化多線程程序的編寫,需要的朋友可以參考下
    2023-11-11
  • Java Array.sort()源碼分析講解

    Java Array.sort()源碼分析講解

    Arrays類中有一個sort()方法,該方法是Arrays類的靜態(tài)方法,在需要對數(shù)組進行排序時,非常的好用。但是sort()的參數(shù)有好幾種,下面我就為大家一一介紹,這幾種形式的用法
    2022-08-08
  • 舉例解析Java多線程編程中需要注意的一些關鍵點

    舉例解析Java多線程編程中需要注意的一些關鍵點

    這篇文章主要介紹了Java多線程編程中需要注意的一些關鍵點,包括ThreadLocal變量與原子更新等一些深層次的內(nèi)容,需要的朋友可以參考下
    2015-11-11
  • Springboot?-?Fat?Jar示例詳解

    Springboot?-?Fat?Jar示例詳解

    這篇文章主要介紹了Springboot?-?Fat?Jar詳解,Spring?Boot內(nèi)嵌容器,通過java?-jar命令便可以直接啟動應用,今天帶著大家探索FAT?JAR啟動的背后原理,需要的朋友可以參考下
    2023-02-02
  • 基于Java解決華為機試實現(xiàn)密碼截取?

    基于Java解決華為機試實現(xiàn)密碼截取?

    這篇文章主要介紹了基于Java解決華為機試實現(xiàn)密碼截取,文章圍繞主題相關資料展開詳細內(nèi)容,具有一的參考價值,需要的小伙伴可以參考一下,希望對你有所幫助
    2022-02-02

最新評論