进程和线程2

本文探讨了Java中的多线程实现,包括使用Runnable和Callable接口,以及线程池的运用。通过示例展示了如何创建线程、获取线程返回值,并解释了线程池的工作原理和优势。此外,还提到了享元模式在减少对象创建、提高性能上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.yan4;

public class Test21 {
	public static void main(String[] args) {
		MyRunnable21[] arr=new MyRunnable21[10];
		for(int i=1;i<=10;i++) {
			MyRunnable21 r=new MyRunnable21((i-1)*100+1, i*100);
			arr[i-1]=r;
			new Thread(r).start();
		}
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		for(int i=0;i<arr.length;i++) {
			System.out.println(arr[i].getRes());
		}
	}
}

class MyRunnable21 implements Runnable{
	private int begin,end,res=0;
	public MyRunnable21(int begin,int end) {
		this.begin=begin;
		this.end=end;
	}
	@Override
	public void run() {
		for(int k=begin;k<=end;k++) {
			res+=k;
		}
	}
	public int getRes() {
		return res;
	}
	
}
package com.yan4;

public class Test22 {
	static int result=0;
	public static void main(String[] args) throws InterruptedException {
		for(int i=1;i<=10;i++) {
			int begin=(i-1)*100+1;
			int end=i*100;
			new Thread(new Runnable() {
				int res=0;
				@Override
				public void run() {
					for(int k=begin;k<=end;k++)
						res+=k;
					result+=res;
				}
			}).start();
		}
		Thread.sleep(2000);
		System.out.println(result);
	}
}

使用Callable接口和Future接口创建线程代码如下:

java.util.concurrent.Callable  有时候java.util.concurrent包可以称为juc包@FunctionalInterface  注解用于声明当前接口是一个函数式接口
public interface Callable<V> {  这里<>中用于声明返回值的类型
   V call() throws Exception;  真正执行的方法,有返回值,允许抛出异常

}

 

线程的构造器为
public Thread(Runnable target) {
      this(null, target, "Thread-" + nextThreadNum(), 0);
  }
  
  Future接口
  public interface Future<V> {
  boolean cancel(boolean mayInterruptIfRunning);  可以取消正在运行的线程
  boolean isCancelled(); 判断是否取消
  boolean isDone(); 判断线程是否在运行中
  V get() throws InterruptedException, ExecutionException; 获取线程执行的结果
  V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;

    Java针对Future接口提供的具体实现类FutureTask
    
    源代码:
    public class FutureTask<V> implements RunnableFuture<V>
    
    public interface RunnableFuture<V> extends Runnable, Future<V>
    
    构造器
      public FutureTask(Callable<V> callable) {
      if (callable == null)
          throw new NullPointerException();
      this.callable = callable;
      this.state = NEW;       // ensure visibility of callable
  }
    
    public void run() {
          Callable<V> c = callable;
          ...
                  result = c.call();
  }

public class Test3 {
	public static void main(String[] args) throws Exception {
		//为了获取返回值,所以需要使用FutureTask中提供的get方法
		FutureTask<Integer>[] arr=new FutureTask[10];
		for(int i=1;i<=10;i++) {
			int begin=(i-1)*100+1;
			int end=i*100;
			//定义Callable的实现
			Callable<Integer> c=new Callable<Integer>() {
				public Integer call() throws Exception {
					int res=0;
					for(int k=begin;k<=end;k++)
						res+=k;
					return res;
				}
			};
//			Runnable r=new FutureTask<>(c);
			//构建FutureTask对象,其中包含Callable对象
			FutureTask<Integer> ft=new FutureTask<>(c);
			//不是必须的,只是证明FutureTask实现类Runnable接口
			Runnable r=ft;
			arr[i-1]=ft;
			//启动线程,构建Thread对象时,要求参数类型为Runnable接口类型
			//线程执行时会自动调用run方法,而FutureTask中提供的run方法会调用Callable对象的call方法
			new Thread(r).start();
		}
		int res=0;
		for(FutureTask<Integer> tmp:arr)
			res+=tmp.get();//main线程执行到这里时,会自动阻塞等待子线程tmp执行结束,执行结束后获取call方法的返回值
		System.out.println(res);
	}
}

注意:FutureTask实现了Future和Runnable接口,所以new Thread(futureTask),当执行thread.start()方法时会自动调用Callable接口实现中的call方法。当调用futureTask.get()方法时可以获取对应的线程对象的执行结果,如果线程并没有返回时,当前线程阻塞等待

使用线程池创建线程

享元模式

享元模式Flyweight Pattern主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式

  •  优点:大大减少对象的创建,降低系统内存的使用,以提高程序的执行效率。
  • 缺点:提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部状态的变化而变化,否则会造成系统的混乱。
public class Test4 {
	public static void main(String[] args) {
		for(int i=0;i<10;i++) {
			IShape tmp=ObjectManager.getInstance();
			System.out.println(tmp);
			ObjectManager.relessInstance(tmp);
		}
	}
}

interface IShape{
	public void draw();
}

class Circle implements IShape{
	@Override
	public void draw() {
		System.out.println("绘制一个圆");
	}
	
}

//共享所有的IShape类型的对象,当需要使用IShape对象时,从对象池中获取一个即可,不是临时创建
//当不需要使用对象时,不是直接释放对象,而是归还对象池
class ObjectManager{
	private static IShape[] arr=new IShape[20];
	static {  //类加载完毕,则在对象池中已经准备了20个对象
		for(int i=0;i<arr.length;i++) {
			arr[i]=new Circle();
		}
	}
	//当需要使用对象时,从对象池中获取一个对象即可
	public static IShape getInstance() {
		IShape res=null;
		for(int i=arr.length-1;i>=0;i--) {
			res=arr[i];
			if(res!=null) {
				arr[i]=null;
				break;
			}
		}
		return res;
	}
	//当不使用对象时,需要归还到对象池中,以供下次需要时再次使用
	public static void relessInstance(IShape obj) {
		for(int i=0;i<arr.length;i++) {
			IShape tmp=arr[i];
			if(tmp==null) {
				arr[i]=obj;
				break;
			}
		}
	}
}

使用ExecutorService、Callable、Future实现有返回结果的线程,线程池的具体实现实际上是依赖于ThreadPoolExecutor

public class Test40 {
	public static void main(String[] args) {
		//固定大小的线程池,容积为3
//		ExecutorService es=Executors.newFixedThreadPool(3);
		//缓存线程池
		ExecutorService es=Executors.newCachedThreadPool();
		
		FutureTask<Integer>[] fs=new FutureTask[10];
		for(int i=1;i<=10;i++) {
			int begin=(i-1)*100+1;
			int end=i*100;
			fs[i-1]=new FutureTask<>(new Callable<Integer>() {
				public Integer call() throws Exception {
					System.out.println(Thread.currentThread());
					int res=0;
					for(int k=begin;k<=end;k++)
						res+=k;
					return res;
				}
			});
			es.submit(fs[i-1]);
		}
		int res=0;
		for(Future<Integer> f:fs) {
			try {
				res+=f.get(1, TimeUnit.SECONDS);
			} catch (InterruptedException | ExecutionException | TimeoutException e) {
				e.printStackTrace();
			}
		}
		System.out.println(res);
	}
}

线程池的好处

  • 重用存在的线程,减少对象创建、消亡的开销,性能佳
  • 可有效控制最大并发线程数,提高系统资源的使用率,同时避免过多资源竞争,避免堵塞
  • 提供定时执行、定期执行、单线程、并发数控制等功能。

线程池的工作原理

  1. 线程池判断核心线程池里的线程是否都在执行任务。如果不是,则创建一个新的工作线程来执行任务。如果核心线程池里的线程都在执行任务,则执行第二步。
  2. 线程池判断工作队列是否已经满。如果工作队列没有满,则将新提交的任务存储在这个工作队列里进行等待。如果工作队列满了,则执行第三步
  3. 线程池判断线程池的线程是否都处于工作状态。如果没有,则创建一个新的工作线程来执行任务。如果已经满了,则交给饱和策略来处理这个任务

 其构造函数如下:

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,  long  keepAliveTime,TimeUnit unit, BlockingQueue<Runnable> workQueue)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值