欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java之線程編程的4種方法實(shí)現(xiàn)案例講解

 更新時(shí)間:2021年08月02日 08:58:18   作者:一只可愛的小狐貍  
這篇文章主要介紹了Java之線程編程的4種方法實(shí)現(xiàn)案例講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

1、繼承Thread

public class T4 {
	public static void main(String[] args) {
		System.out.println(Thread.currentThread());
		Thread t1 = new A1();
		t1.start();
	}
}
class A1 extends Thread{
	@Override
	public void run() {
		for(int i=0;i<10;i++) {
			System.out.println("Thread:"+Thread.currentThread().getName());
		}
	}
}

2、實(shí)現(xiàn)Runnable接口

public class T3 {
	public static void main(String[] args) {
		System.out.println("Thread:"+Thread.currentThread().getName());
		Thread t1 = new Thread(new A2());
		t1.start();
	}

}
class A2 implements Runnable{
	@Override
	public void run() {
		int res =0;
		for(int i=0;i<10;i++) {
			res+=i;
		System.out.println("Thread:"+Thread.currentThread().getName());
		}
	}
}

3、使用Callable和Future接口創(chuàng)建線程

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

public class T2 {
	public static void main(String[] args) throws Exception {
		System.out.println("Test3:" + Thread.currentThread().getName());
		Callable c = new A4();
		FutureTask ft = new FutureTask(c);
		Thread t1 = new Thread(ft);
		t1.start();
		Object res = ft.get();
		System.out.println("結(jié)果:" + res);
	}
}
class A4 implements Callable {
	@Override
	public Object call() throws Exception {
		int res = 0;
		for (int i = 0; i < 10; i++) {
			res += i;
			System.out.println("Thread:" + Thread.currentThread().getName());
		}
		return res;
	}
}

4、使用線程池創(chuàng)建線程

享元模式
享元模式Flyweight Pattern主要用于減少創(chuàng)建對象的數(shù)量,以減少內(nèi)存占用和提高性能。這種類型的設(shè)計(jì)模式屬于 結(jié)構(gòu)型模式,它提供了減少對象數(shù)量從而改善應(yīng)用所需的對象結(jié)構(gòu)的方式
優(yōu)點(diǎn):大大減少對象的創(chuàng)建,降低系統(tǒng)內(nèi)存的使用,以提高程序的執(zhí)行效率。
缺點(diǎn):提高了系統(tǒng)的復(fù)雜度,需要分離出外部狀態(tài)和內(nèi)部狀態(tài),而且外部狀態(tài)具有固有化的性質(zhì),不應(yīng)該隨著內(nèi)部 狀態(tài)的變化而變化,否則會造成系統(tǒng)的混亂。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class T1 {
	public static void main(String[] args) throws Exception {
		Future[] arr = new Future[5];
		ExecutorService es = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 5; i++) {
			arr[i] = es.submit(new A4());
		}
		for (Future f : arr) {
			Object res = f.get();
			System.out.println("結(jié)果為:" + res);
		}
		es.shutdown();
	}
}

class A4 implements Callable {
	@Override
	public Object call() throws Exception {
		int res = 0;
		for (int i = 0; i < 10; i++) {
			res += i;
			System.out.println("Thread" + Thread.currentThread().getName());
		}
		return res;
	}
}

到此這篇關(guān)于Java之線程編程的4種方法實(shí)現(xiàn)案例講解的文章就介紹到這了,更多相關(guān)Java之線程編程的4種方法實(shí)現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論