美文网首页
多线程的创建方式

多线程的创建方式

作者: 垂直居中的句号 | 来源:发表于2022-12-04 22:36 被阅读0次

    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);

    相关文章

      网友评论

          本文标题:多线程的创建方式

          本文链接:https://www.haomeiwen.com/subject/eyhbfdtx.html