1024程序员节日!

1.创建线程的方式?

实现RunnableCallable接口,继承Thread类,使用Executor框架来创建线程池

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class RunnableImpl implements Runnable{

@Override
public void run(){

}


public static void main(String[] args) {
Runnable runnable = new RunnableImpl();
Thread thread = new Thread(runnable);
thread.start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class CallableImpl implements Callable<Integer> {

@Override
public Integer call(){
return 0;
}

public static void main(String[] args) {
Callable<Integer> callable = new CallableImpl();
FutureTask<Integer> result = new FutureTask<>(callable);
Thread thread = new Thread(result);
thread.start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Mythread extends Thread{

private String id;
public Mythread(String id){
this.id =id;
}

public void run(){
for (int i = 0; i < 5 ; i++) {
System.out.println("线程开始"+this.id+"i");
}
}

public static void main(String[] args) {
Mythread mythread1 = new Mythread("mac1");
Mythread mythread2 = new Mythread("mac2");
Mythread mythread3= new Mythread("mac3");

mythread1.start();
mythread2.start();
mythread3.start();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class ThreadPoolExample {

public static void main(String args[]) {
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i =0; i<100; i++){
service.submit(new Task(i));
}
}

}

final class Task implements Runnable{
private int taskId;

public Task(int id){
this.taskId = id;
}

@Override
public void run() {
System.out.println("Task ID : " + this.taskId +" performed by "
+ Thread.currentThread().getName());
}

}

实现RunnableCallable接口有哪些区别?

实现Callable接口能有返回值,而实现Runnable接口没有返回值