1.通过继承Runnable接口实现
public class TestThread1 implements Runnable{
public static void main(String[] args) {
TestThread1 t1 = new TestThread1();
Thread t =new Thread(t1);
t.start();
}
@Override
public void run() {
System.out.println("测试");
}
}
2.通过继承thread类实现:
public class TestThread2 extends Thread{
public static void main(String[] args) {
TestThread2 t1 = new TestThread2();
t1.start();
}
@Override
public void run() {
System.out.println("测试");
}
}
3.通过匿名内部类实现:
public class TestThread3{
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("测试");
}
}).start();
}
}
4.通过FutureTask和Callable接口实现线程的创建
public class TestThread4{
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Task t =new Task();
FutureTask<Integer> fu = new FutureTask<>(t);
Thread thread = new Thread(fu);
thread.start();
try {
System.out.println(fu.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
public class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return 1;
}
}
5.定时器
public class TestThread5{
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定时器"+timer.toString());
}
}, 0,1000);
}
}
6.线程池创建:
public class TestThread6{
public static void main(String[] args) {
ExecutorService e =Executors.newFixedThreadPool(10);
for(int i =0;i<10;i++){
e.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
e.shutdown();
}
}
7.用lambda 表达式
public class TestThread7{
public static void main(String[] args) {
new Thread(()-> System.out.println("thread")).start();
Runnable r =()-> System.out.print("runnable");
r.run();
}
}