博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
线程的编程4种实现方法
阅读量:3968 次
发布时间:2019-05-24

本文共 2233 字,大约阅读时间需要 7 分钟。

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、实现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接口创建线程

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("结果:" + 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、使用线程池创建线程

享元模式

享元模式Flyweight Pattern主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于 结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式
优点:大大减少对象的创建,降低系统内存的使用,以提高程序的执行效率。
缺点:提高了系统的复杂度,需要分离出外部状态和内部状态,而且外部状态具有固有化的性质,不应该随着内部 状态的变化而变化,否则会造成系统的混乱。

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("结果为:" + 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;	}}

转载地址:http://nzjki.baihongyu.com/

你可能感兴趣的文章
Weblogic 简介
查看>>
观察者模式 (Observer)
查看>>
Java 集合框架
查看>>
Weblogic 精萃
查看>>
Servlet 精萃
查看>>
XStream 精萃
查看>>
XStream 环境设置
查看>>
Git 分支
查看>>
Git 冲突
查看>>
Git Merging vs. Rebasing
查看>>
libreoffice/openoffice c/c++转换office格式为pdf
查看>>
Tomcat 7.0 64位免安装解压版 安装及配置
查看>>
Android 网络编程 初级入门(一)
查看>>
No enclosing instance of type Demo06 is accessible.
查看>>
计算机发展中的两大“杀手”
查看>>
MDK5(Keil for ARM) 工程建立时遇到的问题集锦
查看>>
Ubuntu下安装GTK+及Glade开发C应用界面
查看>>
assertion 'GTK_IS_WIDGET (widget)' failed的解决办法
查看>>
Ubuntu登录管理员账户时,输入密码后一直在登录界面循环
查看>>
Linux下的定时器以及POSIX定时器:timer_settime()
查看>>