1、继承thread
public class TestThread {
public static void main(String[] args) {
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.start();
}
}
class ThreadDemo extends Thread{
@Override
public void run() {
boolean flag = false;
for(int i = 3 ; i < 100 ; i ++) {
flag = false;
for(int j = 2; j <= Math.sqrt(i) ; j++) {
if(i % j == 0) {
flag = true;
break;
}
}
if(flag == false) {
System.out.print(i+" ");
}
}
}
}
2、实现runnable
RunnableDemo runnableDemo = new RunnableDemo();
new Thread(runnableDemo).start();
class RunnableDemo implements Runnable{
@Override
public void run() {
boolean flag = false;
for(int i = 3 ; i < 100 ; i ++) {
flag = false;
for(int j = 2; j <= Math.sqrt(i) ; j++) {
if(i % j == 0) {
flag = true;
break;
}
}
if(flag == false) {
System.out.print(i+" ");
}
}
}
3、实现callable,重写call方法
CallableDemo callableDemo = new CallableDemo();
FutureTask futureTask = new FutureTask<>(callableDemo);
new Thread(futureTask).start();
class CallableDemo implements Callable<List<Integer>>{
@Override
public List<Integer> call() throws Exception {
boolean flag = false;
List<Integer> lists = new ArrayList<>();
for(int i = 3 ; i < 100 ; i ++) {
flag = false;
for(int j = 2; j <= Math.sqrt(i) ; j++) {
if(i % j == 0) {
flag = true;
break;
}
}
if(flag == false) {
lists.add(i);
}
}
return lists;
}
}
4、线程池
ExecutorService executorService = Executors.newFixedThreadPool(5);
网友评论