Estuche integral de 36 subprocesos múltiples

Ejemplo completo de subprocesos múltiples

  

Suma y resta digital

[Título] Diseñe cuatro objetos de hilo, dos hilos realizan operaciones de resta y dos hilos realizan operaciones de suma.
  

class Resource{
    
    		//操作资源
	private int num = 0;		//进行加减操作的数据
	private boolean flag = true;		//加减切换,
	//flag=true 表示可以进行加法,不能进行减法
	public synchronized void add() throws Exception {
    
    
		while(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 {
    
    
		while(this.flag == true) {
    
    		//减法操作需要等待
			super.wait();
		}
		Thread.sleep(200);
		this.num --;
		System.out.println("减法操作 - "+ Thread.currentThread().getName()+" - num = " + this.num);
		this.flag = true;		//减法完成,需要执行加法
		super.notifyAll();		//唤醒全部等待线程
	}
}

class AddThread implements Runnable{
    
    		//加法线程
	private Resource resource;
	public AddThread(Resource resource) {
    
    
		this.resource = resource;
	}
	@Override
	public void run() {
    
    
		for(int x =0; x<50; x++) {
    
    
			try {
    
    
				this.resource.add();
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}
		}
	}
}

class SubThread implements Runnable{
    
    		//减法线程
	private Resource resource;
	public SubThread(Resource resource) {
    
    
		this.resource = resource;
	}
	@Override
	public void run() {
    
    
		for(int x =0; x<50; x++) {
    
    
			try {
    
    
				this.resource.sub();
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}
		}
	}
}

public class Num {
    
    
	public static void main(String[] args) {
    
    
		Resource res = new Resource();
		AddThread at = new AddThread(res);
		SubThread su = new SubThread(res);
		new Thread(at,"加法线程 - A").start();
		new Thread(at,"加法线程 - B").start();
		new Thread(su,"减法线程 - X").start();
		new Thread(su,"减法线程 - Y").start();
	}
}

Esta pregunta es una operación de desarrollo clásica de múltiples subprocesos. La esencia central que se debe considerar en el programa es: sume uno, reste uno, y el resultado general del cálculo solo debe alternar entre 0, 1 y -1.

Computadora de producción

[Tema] Diseñar una computadora de producción y mover computadoras. Se requiere mover una computadora cuando se produce una computadora. Si no hay una nueva producción de computadora, el portero debe esperar; si la nueva computadora no se ha movido, la producción debe esperar Y cuente la cantidad de computadoras producidas.
Modelo productor consumidor

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;
		this.count++;
	}
	@Override
	public String toString() {
    
    
		return "num = "+ count +" Computer [name=" + name + ", price=" + price + "]";
	}
}

class Resources {
    
    		//
	private Computer computer;
	public synchronized void product() throws Exception{
    
    
		if(this.computer != null) {
    
    		//已经生产过了
			super.wait();
		}
		Thread.sleep(100);
		this.computer = new Computer("lyz", 1.1);
		System.out.println("生产电脑"+ this.computer);
		super.notifyAll();
	}
	public synchronized void consume() throws Exception {
    
    
		if(this.computer == null) {
    
    		//不能进行搬运
			super.wait();
		}
		Thread.sleep(10);
		this.computer = new Computer("lyz", 1.1);
		super.notifyAll();
		System.out.println("取走电脑"+this.computer);
		this.computer = null;		//已经取走了
		super.notifyAll();
	}
}

class Produced implements Runnable{
    
    
	private Resources resource;
	public Produced(Resources res) {
    
    
		this.resource = res;
	}
	@Override
	public void run() {
    
    
		for(int x =0; x<50;x++) {
    
    
			try {
    
    
				this.resource.product();
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}
		}
	}
}

class Consum implements Runnable{
    
    
	private Resources resource;
	public Consum(Resources res) {
    
    
		this.resource = res;
	}
	@Override
	public void run() {
    
    
		for(int x =0; x<50;x++) {
    
    
			try {
    
    
				this.resource.consume();
			} catch (Exception e) {
    
    
				e.printStackTrace();
			}
		}
	}
}

public class ComputerDemo {
    
    
	public static void main(String[] args) {
    
    
		Resources res = new Resources();
		new Thread(new Produced(res)).start();
		new Thread(new Consum(res)).start();
	}
}

  

Competencia

[Título] Para implementar un programa de respuesta de licitación, se requieren tres respondedores (tres subprocesos) y la instrucción de respuesta se emite al mismo tiempo, y se da un aviso para el éxito o el fracaso de la respuesta.
Dado que una operación de subprocesos múltiples de este tipo debe involucrar el problema de la devolución de datos, es mejor usarla ahoraInvocableEs una forma de procesamiento más conveniente.

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

class AnswerThread implements Callable<String>{
    
    
	private boolean flag = false;
	@Override
	public String call() throws Exception {
    
    
		synchronized (this) {
    
    
			if(this.flag == false) {
    
    		//抢答成功
				this.flag = true;
				return Thread.currentThread().getName() + "抢答成功";
			} else {
    
    
				return Thread.currentThread().getName() + "抢答失败";
			}
		}
	}
}

public class AnswerDemo {
    
    
	public static void main(String[] args) throws Exception{
    
    
		AnswerThread mt  = new AnswerThread();
		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());
	}
}

Supongo que te gusta

Origin blog.csdn.net/MARVEL_3000/article/details/111567531
Recomendado
Clasificación