实现多线程的方式
继承Thead类
public class ThreadDemo extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
ThreadDemo demo = new ThreadDemo();
demo.start();
}
}
}
实现Runnable接口
public class RunableThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
RunableThread runableThread = new RunableThread();
for (int i = 0; i < 100; i++) {
new Thread(runableThread).start();
}
}
}
实现Callable接口有返回值的线程
public class CallableAndFuture implements Callable<String> {
@Override
public String call() throws Exception {
return Thread.currentThread().getName();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<String> task = new FutureTask<String>(new CallableAndFuture());
new Thread(task).start();
System.out.println(task.get());
}
}
评论
0 评论