1.继承Thread类创建线程
package com.practise.createthread;
public class AnonymousThread {
public static void main(String[] args) {
new Thread("线程一") {
public void run() {
for(int i=1;i<=20;i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}.start();
Thread.currentThread().setName("主线程");
for(int i=1;i<=20;i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
2.实现Runnable接口创建线程
package com.practise.createthread;
public class AnonymousThread {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<=20;i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}, "线程二").start();
Thread.currentThread().setName("主线程");
for(int i=1;i<=20;i++) {
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
3.使用Callable和Future创建线程
package com.practise.createthread;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class AnonymousThread {
public static void main(String[] args) {
FutureTask<Integer> task=new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() {
Integer total = 0;
try {
for (int i = 1; i <= 50; i++) {
total += i;
}
return total;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
});
new Thread(task, "有返回值的线程").start();
try {
System.out.println(task.get());
} catch (Exception ex) {
ex.printStackTrace();
}
Thread.currentThread().setName("主线程");
for (int i = 1; i <= 20; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}