public class Test01_01 extends Thread{ @Override public void run() { for (int i = 0; i < 5; i++) { logger.info("thread sout:"+i); } } }
运行方式如下
language-java
1 2
Thread t = new Test01_01(); t.start();
其二
实现Runnable接口,重写run方法,这种方式避免了无法继承别的类的缺陷。
language-java
1 2 3 4 5 6 7 8 9 10 11 12
public class Test02_01 implements Runnable{ @Override public void run() { Thread cut = Thread.currentThread(); for (int i = 0; i < 5; i++) { System.out.println("thread ["+cut.getName()+"]"+i); } } }
运行方式如下
language-java
1 2
Runnable target = new Test02_01(); new Thread(target).start();
或者使用lambda表达式
language-java
1 2 3 4 5 6 7 8
new Thread(()->{ Thread cut = Thread.currentThread(); for (int i = 0; i < 5; i++) { System.out.println("thread ["+cut.getName()+"]"+i); } }).start();
其三
实现Callable接口,重写call方法,这种方式可以取得线程的返回值。
language-java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
private static class Test04_01 implements Callable<Long>{ @Override public Long call() throws Exception { Thread cut = Thread.currentThread(); System.out.println("当前线程:"+cut.getName()); long res = 0; for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { res += j; } } return res; } };
运行方式如下
language-java
1 2 3 4 5
Callable<Long> call = new Test04_01(); FutureTask<Long> task = new FutureTask<>(call); new Thread(task).start(); Long l = task.get(); System.out.println(l);
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 5, 8, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
public class PostLock01 { private static class MyRunnable01 implements Runnable{ private int number; @Override public void run() { for (int i = 0; i < 1000; i++) { synchronized (this){ ++number; } } } }; private static class MyRunnable02 implements Runnable{ // private int number; private AtomicInteger number = new AtomicInteger(); @Override public void run() { for (int i = 0; i < 1000; i++) { number.incrementAndGet(); } } };