java创建线程几种_java中创建线程有几种方式
詳細內容
線程的創建方式
1、繼承Thread類實現多線程
2、覆寫Runnable()接口實現多線程,而后同樣覆寫run()。推薦此方式
3、使用Callable和Future創建線程
相關視頻教程推薦:java學習視頻
實例如下:
1、繼承Thread類實現多線程/*
* 繼承Thread類創建線程
* 1、重寫run方法
* 2、創建thread類的實例,即創建線程對象
* 3、調用線程對象的start()來啟動該線程
* 注意:Thread類的每個進程之間不能共享該實例變量;具有單繼承局限
* */
public class StartThread extends Thread{
private int i;
@Override
//重寫run方法
public void run() {
// TODO Auto-generated method stub
for(i=0;i<10;i++) {
System.out.println(getName()+" "+i);
}
}
public static void main(String[] args) {
for(int i=0;i<10;i++) {
System.out.println(Thread.currentThread().getName()+ " ,"+i);
//創建thread類的實例
StartThread h1=new StartThread();
StartThread h2=new StartThread();
if(i==2) {
//啟動第一個進程
h1.start();
//啟動第二個進程
h2.start();
}
}
}
}
2、覆寫Runnable()接口實現多線程,而后同樣覆寫run()
定義Runnable()接口的實現類,重寫Run()方法。
創建Runnable實現類的實例,并以此實例作為Thread的target來創建Thread對象。這個Thread對象才是真正的線程對象
通過調用線程對象的start()方法來啟動線程/*創建線程方式二
* 1、創建:實現Runnable+重寫run
* 2、啟動:創建實現類對象+Thread對象+start
*
* 注意:推薦使用,避免單繼承的局限性,優先使用接口
* 方便共享資源
* */
public class MyThread2 implements Runnable {//實現Runnable接口
public void run(){
//重寫run方法
// TODO Auto-generated method stub
//當線程類實現Runnable接口時
//如果想要獲取當前線程,只能使用Thread.currentThread方法
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
}
public class Main {
public static void main(String[] args){
//啟動線程1
//不像繼承Thread類一樣,直接可以實例化對象即可,Runnable接口必須要
//先創建實例,再將此實例作為Thread的target來創建Thread對象
//創建并啟動線程
MyThread2 myThread=new MyThread2();
Thread thread=new Thread(myThread);
thread().start();
//或者 new Thread(new MyThread2()).start();
}
}
3、使用Callable和Future創建線程
和Runnable接口不一樣,Callable接口提供了一個call()方法作為線程執行體,call()方法比run()方法功能要強大。
call()方法可以有返回值
call()方法可以聲明拋出異常public class Main {
public static void main(String[] args){
MyThread3 th=new MyThread3();
//使用Lambda表達式創建Callable對象
//使用FutureTask類來包裝Callable對象
FutureTask future=new FutureTask(
(Callable)()->{
return 5;
}
);
//實質上還是以Callable對象來創建并啟動線程
new Thread(task,"有返回值的線程").start();
try{
//get()方法會阻塞,直到子線程執行結束才返回
System.out.println("子線程的返回值:"+future.get());
}catch(Exception e){
ex.printStackTrace();
}
}
}
相關文章教程推薦:java編程入門
總結
以上是生活随笔為你收集整理的java创建线程几种_java中创建线程有几种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: displayprime java_ja
- 下一篇: 指数函数中x的取值范围_谨记!高考数学中