您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java中如何实现多线程?(代码示例)

2025/12/28 5:34:38发布22次查看
本篇文章给大家带来的内容是java中如何实现多线程?(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
方法一:继承类,覆盖方法run()
我们在创建的thread类的子类中重写run() ,加入线程所要执行的代码即可。
下面是一个例子:
 public class mythread extends thread{ int count= 1, number; public mythread(int num) {number = num;system.out.println("创建线程 " + number); } public void run() {while(true) { system.out.println("线程 " + number + ":计数 " + count); if(++count== 6) return;}}public static void main(string args[]){ for(int i = 0;i 〈 5; i++) new mythread(i+1).start();} }
这种方法简单明了,符合大家的习惯,但是,它也有一个很大的缺点,那就是如果我们的类已经从一个类继承(如小程序必须继承自 applet 类),则无法再继承 thread 类,这时如果我们又不想建立一个新的类,应该怎么办呢?
我们不妨来探索一种新的方法:我们不创建thread类的子类,而是直接使用它,那么我们只能将我们的方法作为参数传递给 thread 类的实例,有点类似回调函数。但是 java 没有指针,我们只能传递一个包含这个方法的类的实例。
那么如何限制这个类必须包含这一方法呢?当然是使用接口!(虽然抽象类也可满足,但是需要继承,而我们之所以要采用这种新方法,不就是为了避免继承带来的限制吗?)
java 提供了接口 java.lang.runnable 来支持这种方法。
方法二:实现 runnable 接口
runnable接口只有一个方法run(),我们声明自己的类实现runnable接口并提供这一方法,将我们的线程代码写入其中,就完成了这一部分的任务。但是runnable接口并没有任何对线程的支持,我们还必须创建thread类的实例,这一点通过thread类的构造函数 public thread(runnable target);来实现。下面是一个例子:
public class mythread implements runnable{ int count= 1, number; public mythread(int num) {number = num;system.out.println("创建线程 " + number); } public void run() {while(true){ system.out.println ("线程 " + number + ":计数 " + count); if(++count== 6) return;} } public static void main(string args[]) {for(int i = 0; i 〈 5;i++) new thread(new mythread(i+1)).start(); }}
严格地说,创建thread子类的实例也是可行的,但是必须注意的是,该子类必须没有覆盖 thread类的 run 方法,否则该线程执行的将是子类的 run 方法,而不是我们用以实现runnable 接口的类的 run 方法,对此大家不妨试验一下。
使用 runnable 接口来实现多线程使得我们能够在一个类中包容所有的代码,有利于封装,它的缺点在于,我们只能使用一套代码,若想创建多个线程并使各个线程执行不同的代码,则仍必须额外创建类,如果这样的话,在大多数情况下也许还不如直接用多个类分别继承 thread 来得紧凑。
方法三、使用executorservice、callable、future实现有返回结果的多线程executorservice、callable、future这个对象实际上都是属于executor框架中的功能类。想要详细了解executor框架的可以访问http://www.javaeye.com/topic/366591 ,这里面对该框架做了很详细的解释。返回结果的线程是在jdk1.5中引入的新特征,确实很实用,有了这种特征我就不需要再为了得到返回值而大费周折了,而且即便实现了也可能漏洞百出。
可返回值的任务必须实现callable接口,类似的,无返回值的任务必须runnable接口。执行callable任务后,可以获取一个future的对象,在该对象上调用get就可以获取到callable任务返回的object了,再结合线程池接口executorservice就可以实现传说中有返回结果的多线程了。下面提供了一个完整的有返回结果的多线程测试例子,在jdk1.5下验证过没问题可以直接使用。代码如下:
import java.util.concurrent.*; import java.util.date; import java.util.list; import java.util.arraylist; @suppresswarnings("unchecked") public class test { public static void main(string[] args) throws executionexception, interruptedexception { system.out.println("----程序开始运行----"); date date1 = new date(); int tasksize = 5; // 创建一个线程池 executorservice pool = executors.newfixedthreadpool(tasksize); // 创建多个有返回值的任务 list list = new arraylist(); for (int i = 0; i < tasksize; i++) { callable c = new mycallable(i + " "); // 执行任务并获取future对象 future f = pool.submit(c); // system.out.println(">>>" + f.get().tostring()); list.add(f); } // 关闭线程池 pool.shutdown(); // 获取所有并发任务的运行结果 for (future f : list) { // 从future对象上获取任务的返回值,并输出到控制台 system.out.println(">>>" + f.get().tostring()); } date date2 = new date(); system.out.println("----程序结束运行----,程序运行时间【" + (date2.gettime() - date1.gettime()) + "毫秒】"); } } class mycallable implements callable { private string tasknum; mycallable(string tasknum) { this.tasknum = tasknum; } public object call() throws exception { system.out.println(">>>" + tasknum + "任务启动"); date datetmp1 = new date(); thread.sleep(1000); date datetmp2 = new date(); long time = datetmp2.gettime() - datetmp1.gettime(); system.out.println(">>>" + tasknum + "任务终止"); return tasknum + "任务返回运行结果,当前任务时间【" + time + "毫秒】"; } }
代码说明:
上述代码中executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了executorservice接口。
public static executorservice newfixedthreadpool(int nthreads)
创建固定数目线程的线程池。
public static executorservice newcachedthreadpool()
创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static executorservice newsinglethreadexecutor()
创建一个单线程化的executor。
public static scheduledexecutorservice newscheduledthreadpool(int corepoolsize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代timer类。
executoreservice提供了submit()方法,传递一个callable,或runnable,返回future。如果executor后台线程池还没有完成callable的计算,这调用返回future对象的get()方法,会阻塞直到计算完成。
综上所述,以上方法各有千秋,大家可以灵活运用。
以上就是java中如何实现多线程?(代码示例)的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product