方法一:
public class Demo extends Thread {
public void run() {
int i=0 ;
for( ;i<100;i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args) {
for(int i=0 ;i<100 ;i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
if(i==20) {
new Demo().start();
new Demo().start();
}
}
}
}
方法二:
public class Demo implements Runnable {
@Override
public void run() {
int i=0 ;
for(;i<100;i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args) {
for(int i=0 ;i<100 ;i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
if(i==20) {
Demo target = new Demo() ;
new Thread(target, "新线程2").start();
new Thread(target, "新线程2").start();
}
}
}
}
方法三:
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Demo {
public static void main(String[] args) throws Exception {
FutureTask<Integer> futureTask = new FutureTask<>((Callable<Integer>)() -> {
int i=0 ;
for(;i<100;i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
return i ;
}) ;
for(int i=0 ;i<100 ;i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
if(i==20) {
new Thread(futureTask, "有返回值线程1").start();
new Thread(futureTask, "有返回值线程2").start();
}
}
System.out.println("返回值为:" + futureTask.get()); ;
}
}