更新時間:2022-09-06 08:21:37 來源:動力節(jié)點 瀏覽1568次
線程可以稱為輕量級進程。線程使用較少的資源來創(chuàng)建和存在于進程中;線程共享進程資源。Java的主線程是程序啟動時啟動的線程。從屬線程是主線程的結(jié)果。這是完成執(zhí)行的最后一個Java線程。
可以通過以下方式以編程方式創(chuàng)建線程:
實現(xiàn)java.lang.Runnable接口。
擴展java.lang.Thread類。
您可以通過實現(xiàn)可運行接口并覆蓋 run() 方法來創(chuàng)建線程。然后,您可以創(chuàng)建一個線程對象并調(diào)用 start() 方法。
Thread 類提供了用于創(chuàng)建和操作線程的構(gòu)造函數(shù)和方法。該線程擴展了 Object 并實現(xiàn)了 Runnable 接口。
// 啟動一個新創(chuàng)建的線程。
// 線程從新狀態(tài)轉(zhuǎn)移到可運行狀態(tài)
// 當它有機會時,執(zhí)行目標 run() 方法
公共無效開始()
任何具有打算由線程執(zhí)行的實例的類都應(yīng)該實現(xiàn) Runnable 接口。Runnable 接口只有一個方法,稱為 run()。
// 線程動作被執(zhí)行
公共無效運行()
與進程相比,Java 線程更輕量級;創(chuàng)建線程需要更少的時間和資源。
線程共享其父進程的數(shù)據(jù)和代碼。
線程通信比進程通信簡單。
線程之間的上下文切換通常比進程之間的切換便宜。
常見的錯誤是使用 run() 而不是 start() 方法啟動線程。
線程 myThread = new Thread(MyRunnable());
myThread.run(); //應(yīng)該是start();
您創(chuàng)建的線程不會調(diào)用 run() 方法。相反,它由創(chuàng)建myThread的線程調(diào)用。
import java.io.*;
class GFG extends Thread {
public void run()
{
System.out.print("Welcome to bjpowernode.");
}
public static void main(String[] args)
{
GFG g = new GFG(); // creating thread
g.start(); // starting thread
}
}
輸出
Welcome to bjpowernode
import java.io.*;
class GFG implements Runnable {
public static void main(String args[])
{
// create an object of Runnable target
GFG gfg = new GFG();
// pass the runnable reference to Thread
Thread t = new Thread(gfg, "gfg");
// start the thread
t.start();
// get the name of the thread
System.out.println(t.getName());
}
@Override public void run()
{
System.out.println("Inside run method");
}
}
輸出
gfg
Inside run method
通過上述介紹,相信大家對Java線程創(chuàng)建方式已經(jīng)有所了解,大家如果想了解更多相關(guān)知識,不妨來關(guān)注一下動力節(jié)點的Java基礎(chǔ)教程技術(shù)文檔,里面還有更豐富的知識等著大家去學(xué)習(xí),相信對大家一定會有所幫助的。