您的位置:首页 > 其它

创建线程的三种方式

2017-03-19 17:23 369 查看
创建线程一共有三种方式:

方式1 继承Thread类

public class ThreadDemo01 extends Thread {
public void run() {
for(int i = 0;i<50;i++){
System.out.println("Thread Name = "+Thread.currentThread().getName()+"--"+i);
}
}

public static void main(String[] args) {
new ThreadDemo01().start();
for(int i = 0;i<50;i++){
System.out.println("Thread Name = "+Thread.currentThread().getName()+"--"+i);
}
}
}


方式2 实现Runnable接口 解决继承Thread的单根继承问题

public class ThreadDemo02 implements Runnable {
public void run() {
for(int i = 0;i<50;i++){
System.out.println("Thread Name = "+Thread.currentThread().getName()+"--"+i);
}
}

public static void main(String[] args) {
new Thread(new ThreadDemo02()).start();
for(int i = 0;i<50;i++){
System.out.println("Thread Name = "+Thread.currentThread().getName()+"--"+i);
}
}
}


方式3 实现Callable接口 解决run方法不能有返回值和不能抛出异常的问题

public class ThreadDemo03 implements Callable<Integer> {

public Integer call() throws Exception {
int count = 0;
for(int i = 0;i<50;i++){
count ++;
System.out.println("Thread Name = "+Thread.currentThread().getName()+"--"+i);
}
return count;
}

public static void main(String[] args) throws InterruptedException, ExecutionException {
ThreadDemo03 demo03 = new ThreadDemo03();
FutureTask<Integer> ft = new FutureTask<Integer>(demo03);
new Thread(ft).start();
for(int i = 0;i<50;i++){
System.out.println("Thread Name = "+Thread.currentThread().getName()+"--"+i);
}
System.out.println("总共执行:"+ft.get()+"次");//尝试了几次,如果将这句放在for循环之前,将不能异步输出
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程