ZUI易入门Android之五种创建线程的方式

tech2022-10-17  116

1.多线程创建方式

Thread的创建方式

Thread thread = new Thread() {

@Override

    public void run() {

            System.out.println("Thread started!");

    }

};

thread.start();

2.Runnable的创建方式

Runnable runnable = new Runnable() {

@Override

public void run() {

           System.out.println("Thread with Runnable started!");

}

};

Thread thread = new Thread(runnable); thread.start();

3.ThreadFactory创建方式

ThreadFactory factory = new ThreadFactory() {

        int count = 0;

       @Override

       public Thread newThread(Runnable r) { count ++;

                return new Thread(r, "Thread-" + count);

      }

};

Runnable runnable = new Runnable() {

@Override

public void run() {

        System.out.println(Thread.currentThread().getName() + "started!");

}

Thread thread = factory.newThread(runnable);

thread.start();

Thread thread1 = factory.newThread(runnable); thread1.start();

4.Executor 和线程池

常用:newCachedThreadPool()

Runnable runnable = new Runnable() {

@Override

public void run() {

               System.out.println("Thread with Runnable started!");

     }

};

Executor executor = Executors.newCachedThreadPool();

executor.execute(runnable); executor.execute(runnable); executor.execute(runnable);

短时批量处理:newFixedThreadPool()

ExecutorService executor = Executors.newFixedThreadPool(20); for (Bitmap bitmap : bitmaps) {

                 executor.execute(bitmapProcessor(bitmap));

}

executor.shutdown();

5.Callable Future创建方式

Callable<String> callable = new Callable<String>() {

@Override

public String call() {

try {

          Thread.sleep(1500);

} catch (InterruptedException e) { e.printStackTrace();

}

      return "Done!";

}

};

ExecutorService executor = Executors.newCachedThreadPool();

Future<String> future = executor.submit(callable); try {

String result = future.get(); System.out.println("result: " + result);

} catch (InterruptedException | ExecutionException e) { e.printStackTrace();

}

 

最新回复(0)