1.通过继承 Thread 类,重写run方法
public class Text extends Thread {
public void run() {
for (int i = 0; i < 101; i++) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ":" + i);
}
}
public static void main(String[] args) {
Text text = new Text();
Text text1 = new Text();
text.start();
text1.start();
}
}
2.通过实现 Runnable 接口,重写run方法
public class Text1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 101; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
public static void main(String[] args) {
Text1 text1 = new Text1();
Text1 text2 = new Text1();
//产生俩个线程去包装这两个任务text1,text2
//新建状态
Thread thread = new Thread(text1);
Thread thread1 = new Thread(text2);
thread.start();
thread1.start();
}
}
3.通过 Callable 和 Future 创建线程
a)创建 Callable 接口的实现类,并实现 call()方法,该 call()方法将作为 线程执行体,并且有返回值(类似于 run()方法)。
b)创建 Callable 实现类的实例,使用 FutureTask 类来包装 Callable 对象, 该 FutureTask 对象封装了该 Callable 对象的 call()方法的返回值。
c)使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。
d)调用 FutureTask 对象的 get()方法来获得子线程执行结束后的返回值。
public class Text2 implements Callable {
@Override
//重写call方法,这个方法有返回结果,其它跟run方法一致
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i < 101; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
sum += i;
}
return "1-100之和:" + sum;
}
public static void main(String[] args) throws Exception {
Text2 text2 = new Text2();
Text2 text3 = new Text2();
FutureTask fu1 = new FutureTask(text2);
FutureTask fu2 = new FutureTask(text3);
Thread t1 = new Thread(fu1);
Thread t2 = new Thread(fu2);
t1.start();
t2.start();
//获取到返回结果
Object result1 = fu1.get();
Object result2 = fu2.get();
System.out.println(result1);
System.out.println(result2);
}
}