赤水市建设局官方网站,房子装修风格大全2021新款,可以发广告的平台,安徽六安毛坦厂中学在Java中#xff0c;有三种方式创建多线程#xff0c;继承类Thread#xff0c;继承接口Runnable#xff0c;继承接口Callable。其中Thread和Runnable需要重写方法run#xff0c;方法run没有返回值#xff1b;Callable需要重写方法call#xff0c;方法call可以返回值。
…在Java中有三种方式创建多线程继承类Thread继承接口Runnable继承接口Callable。其中Thread和Runnable需要重写方法run方法run没有返回值Callable需要重写方法call方法call可以返回值。
Thread实现如下
package ch01;/*** copyright 2003-2024* author qiao wei* date 2024-01-04 15:47* version 1.0* brief * history */
public class MyThread extends Thread {Overridepublic void run() {super.run();for (int index 0; 100 ! index; index) {System.out.println(----------子线程 index , Thread.currentThread().threadId());}}
}Runnable实现如下
package ch01;/*** copyright 2003-2024* author qiao wei* date 2024-01-04 15:58* version 1.0* brief * history */
public class MyRunnable implements Runnable {public MyRunnable() {}Overridepublic void run() {for (int index 0; 100 ! index; index) {System.out.println(----------子线程 index , Thread.currentThread().threadId());}}
}Callable实现如下
package ch01;import java.util.concurrent.Callable;/*** copyright 2003-2024* author qiao wei* date 2024-01-04 16:21* version 1.0* brief 继承接口Callable进行多线程。* history */
public class MyCallable implements CallableString {public MyCallable(int count) {this.count count;}/*** author qiao wei* brief 通过程序处理返回响应值。* param * return 返回处理后的Integer数据。* throws */Overridepublic String call() throws Exception {int sum 0;for (int index 0; index ! count; index) {sum index;}// 有返回值。return Integer.toString(sum);}private int count;
}