Java多線程的在開發(fā)中用到的很多,簡單總結(jié)一下幾種寫法,分別是繼承Thread方法,實(shí)現(xiàn)Runnable接口,實(shí)現(xiàn)Callable接口;
1.繼承Thread方法
class TestThread extends Thread{
String name;
public TestThread(String name){
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 6; i++) {
System.out.println(this.name+":"+i);
}
}
}
main方法調(diào)用:
Thread啟動(dòng)有兩個(gè)方法,一個(gè)是start()方法,一個(gè)是run()方法,但是直接調(diào)用run方法時(shí)線程不會(huì)交替運(yùn)行,而是順序執(zhí)行,只有用start方法時(shí)才會(huì)交替執(zhí)行
TestThread tt1 = new TestThread("A");
TestThread tt2 = new TestThread("B");
tt1.start();
tt2.start();
運(yùn)行結(jié)果:
2.實(shí)現(xiàn)Runnable接口,有多種寫法
2.1外部類
class TestRunnable implements Runnable{
String name;
public TestRunnable(String name){
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 6; i++) {
System.out.println(this.name+":"+i);
}
}
}
調(diào)用:
TestRunnable tr1 = new TestRunnable("C");
TestRunnable tr2 = new TestRunnable("D");
new Thread(tr1).start();
new Thread(tr2).start();
2.2匿名內(nèi)部類方式
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).start();
2.3 Lamda表達(dá)式,jdk1.8,只要是函數(shù)式接口,都可以使用Lamda表達(dá)式或者方法引用
new Thread(()->{
for (int i = 0; i < 6; i++) {
System.out.println(i);
}
}).start();
2.4ExecutorService創(chuàng)建線程池的方式
class TestExecutorService implements Runnable{
String name;
public TestExecutorService(String name){
this.name=name;
}
@Override
public void run() {
for (int i = 0; i < 6; i++) {
System.out.println(this.name+":"+i);
}
}
}
調(diào)用:可以創(chuàng)建固定個(gè)數(shù)的線程池
ExecutorService pool = Executors.newFixedThreadPool(2);
TestExecutorService tes1 = new TestExecutorService("E");
TestExecutorService tes2 = new TestExecutorService("F");
pool.execute(tes1);
pool.execute(tes2);
pool.shutdown();
運(yùn)行結(jié)果跟2.1差不多
3.實(shí)現(xiàn)Callable接口,可以返回結(jié)果
//Callable<V>提供返回?cái)?shù)據(jù),根據(jù)需要返回不同類型
class TestCallable implements Callable<String>{
private int ticket = 5;
@Override
public String call() throws Exception {
for (int i = 0; i < 5; i++) {
if(this.ticket>0)
System.out.println("買票,ticket="+this.ticket--);
}
return "票賣完了";
}
}
調(diào)用:
Callable<String> tc = new TestCallable();
FutureTask<String> task = new FutureTask<String>(tc);
new Thread(task).start();
try {
System.out.println(task.get());//獲取返回值
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
運(yùn)行結(jié)果:
名稱欄目:Java多線程的幾種寫法-創(chuàng)新互聯(lián)
新聞來源:http://www.rwnh.cn/article30/dhphso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護(hù)、云服務(wù)器、虛擬主機(jī)、微信小程序、靜態(tài)網(wǎng)站、服務(wù)器托管
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容