add more demo for creating new thred

This commit is contained in:
Jason Lu 2025-02-17 13:36:08 +08:00
parent f5472740be
commit cc0ecc57bb
6 changed files with 119 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package createthread;
public class CreateByAnonymousClass {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("create thread by using anonymous class");
}
}).start();
new Thread(() -> {
System.out.println("create thread by using lambda");
}).start();
}
}

View File

@ -0,0 +1,30 @@
package createthread;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class CreateByCompletableFuture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
System.out.println("create thread by using CompletableFuture. Returning results...");
return "hello!";
});
while (true) {
if (cf.isDone()) {
System.out.println(cf.get());
break;
}
}
// try {
// Thread.sleep(0);
// System.out.println(cf.get());
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// throw new RuntimeException(e);
// }
}
}

View File

@ -0,0 +1,18 @@
package createthread;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
public class CreateByForkJoin {
public static void main(String[] args) {
ForkJoinPool forkJoinPool = new ForkJoinPool();
forkJoinPool.execute(() -> {
System.out.println("create thread by using forkjoin 10A...");
});
List<String> list = Arrays.asList("10B......");
list.parallelStream().forEach(System.out::println);
}
}

View File

@ -0,0 +1,18 @@
package createthread;
import java.util.concurrent.FutureTask;
public class CreateByFutureTask {
public static void main(String[] args)
{
FutureTask<String> futureTask = new FutureTask<>(() -> "Create by FutureTask");
new Thread(futureTask).start();
try {
System.out.println(futureTask.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,18 @@
package createthread;
public class CreateByThreadGroup {
public static void main(String[] args) {
ThreadGroup threadGroup = new ThreadGroup("threadGroup");
new Thread(threadGroup, () -> {
System.out.println("6-T1......");
},"T1").start();
new Thread(threadGroup, () -> {
System.out.println("6-T2......");
},"T2").start();
new Thread(threadGroup, () -> {
System.out.println("6-T3......");
},"T3").start();
}
}

View File

@ -0,0 +1,18 @@
package createthread;
import java.util.Timer;
import java.util.TimerTask;
public class CreateByTimer {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("create thread by using timer");
}
}, 0, 1000);
}
}