1.通過runnable接口實現多線程
實現runnable接口的類ThreadDemo,需要用new Thread(ThreadDemo實例).start() 去運行。
public class ThreadDemo implements Runnable {
private String name;
public ThreadDemo() {
}
public ThreadDemo(String name) {
this.name = name;
System.out.println("create thread name :"+name);
}
@Override
public void run() {
System.out.println("run thread name : " + name);
for (int i=0; i<5; i++) {
System.out.println("this is " + i + " th");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
System.out.println("this thread: "+name+" has exception interrupted");
}
}
System.out.println("this thread: "+name+"is over");
}
}
public class ThreadMain {
public static void main(String[] args) {
ThreadDemo t1 = new ThreadDemo("thread1");
new Thread(t1).start();
ThreadDemo t2 = new ThreadDemo("thread2");
new Thread(t2).start();
}
}
runnable接口是函數式藉口,所以可以使用lambda表達式
public class ThreadMain {
public static void main(String[] args) {
new Thread(()->{
for (int i=0; i<5; i++) {
System.out.println("this is :" + i);
}
}).start();
}
}
2.繼承thread類實現多線程。
public class ThreadClassImpl extends Thread {
private String name;
public ThreadClassImpl() {
}
public ThreadClassImpl(String name) {
this.name = name;
System.out.println("create thread name :"+name);
}
@Override
public void run() {
System.out.println("run thread name : " + name);
for (int i=0; i<5; i++) {
System.out.println("this is " + i + " th");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
System.out.println("this thread: "+name+" has exception interrupted");
}
}
System.out.println("this thread: "+name+"is over");
}
}
public class ThreadMain {
public static void main(String[] args) {
ThreadClassImpl impl1 = new ThreadClassImpl("thread_1");
impl1.start();
ThreadClassImpl impl2 = new ThreadClassImpl("thread_2");
impl2.start();
}
}
3.callable帶返回參數的方式:
import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadTestStudy {
public static void main(String ards[]) {
List<FutureTask> listResult = Lists.newArrayList();
for(int i=0;i<10;i++){
Callable<Integer> implCallable = new ImplCallable();
FutureTask<Integer> futureTask = new FutureTask<Integer>(implCallable);
new Thread(futureTask).start();
listResult.add(futureTask);
//System.out.println(Thread.currentThread().getName()+"----"+futureTask.get());
}
listResult.stream().forEach(futureTask -> {
try {
System.out.println("=======>>>>>>>" + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
System.out.println(Thread.currentThread().getName());
}
}
class ImplCallable implements Callable<Integer>{
volatile static int testNum = 0;
@Override
public Integer call() throws Exception {
int result = 0;
for(int i=0;i<10;i++){
result += i;
}
testNum++;
result += testNum;
//System.out.println(Thread.currentThread().getName());
return result;
}
}
4.使用線程的方式
(1)runnable方式
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadTestStudyPoolRun {
public static void main(String[] args){
//使用Executors工具類中的方法創建線程池
ExecutorService pool = Executors.newFixedThreadPool(5);
ThreadPoolDemo demo = new ThreadPoolDemo();
//爲線程池中的線程分配任務,使用submit方法,傳入的參數可以是Runnable的實現類,也可以是Callable的實現類
for(int i=1;i<=5;i++){
pool.submit(demo);
}
//關閉線程池
//shutdown : 以一種平和的方式關閉線程池,在關閉線程池之前,會等待線程池中的所有的任務都結束,不在接受新任務
//shutdownNow : 立即關閉線程池
pool.shutdown();
}
}
class ThreadPoolDemo implements Runnable{
/**多線程的共享數據*/
private int i = 0;
@Override
public void run() {
while(i<=50){
System.out.println(Thread.currentThread().getName()+"---"+ i++);
}
}
}
(2)callable方式
import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadPoolCallable {
public static void main(String args[]){
ExecutorService executorService = Executors.newFixedThreadPool(5);
List<Future> futureList = Lists.newArrayList();
for(int i=0;i<5;i++){
/*Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int result = 0;
for(int i=0;i<=10;i++){
result += i;
}
return result;
}
});*/
CallablePoolUtil poolUtil = new CallablePoolUtil();
Future<Integer> future = executorService.submit(poolUtil);
futureList.add(future);
}
futureList.stream().forEach(futureTask -> {
try {
System.out.println("=======>>>>>>>" + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
executorService.shutdown();
}
}
class CallablePoolUtil implements Callable<Integer> {
volatile static int testNum = 0;
@Override
public Integer call() throws Exception {
int result = 0;
for(int i=0;i<10;i++){
result += i;
}
testNum++;
result += testNum;
//System.out.println(Thread.currentThread().getName());
return result;
}
}
其他相關:
1.completableFuture方式實現多線程:https://mp.csdn.net/console/editor/html/104949964
借鑑與學習
1.https://blog.csdn.net/qq_44238142/article/details/90647393
2.https://www.cnblogs.com/duanjiapingjy/p/9434244.html