更新時(shí)間:2022-09-06 08:21:37 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1413次
線程可以稱為輕量級(jí)進(jìn)程。線程使用較少的資源來創(chuàng)建和存在于進(jìn)程中;線程共享進(jìn)程資源。Java的主線程是程序啟動(dòng)時(shí)啟動(dòng)的線程。從屬線程是主線程的結(jié)果。這是完成執(zhí)行的最后一個(gè)Java線程。
可以通過以下方式以編程方式創(chuàng)建線程:
實(shí)現(xiàn)java.lang.Runnable接口。
擴(kuò)展java.lang.Thread類。
您可以通過實(shí)現(xiàn)可運(yùn)行接口并覆蓋 run() 方法來創(chuàng)建線程。然后,您可以創(chuàng)建一個(gè)線程對(duì)象并調(diào)用 start() 方法。
Thread 類提供了用于創(chuàng)建和操作線程的構(gòu)造函數(shù)和方法。該線程擴(kuò)展了 Object 并實(shí)現(xiàn)了 Runnable 接口。
// 啟動(dòng)一個(gè)新創(chuàng)建的線程。
// 線程從新狀態(tài)轉(zhuǎn)移到可運(yùn)行狀態(tài)
// 當(dāng)它有機(jī)會(huì)時(shí),執(zhí)行目標(biāo) run() 方法
公共無效開始()
任何具有打算由線程執(zhí)行的實(shí)例的類都應(yīng)該實(shí)現(xiàn) Runnable 接口。Runnable 接口只有一個(gè)方法,稱為 run()。
// 線程動(dòng)作被執(zhí)行
公共無效運(yùn)行()
與進(jìn)程相比,Java 線程更輕量級(jí);創(chuàng)建線程需要更少的時(shí)間和資源。
線程共享其父進(jìn)程的數(shù)據(jù)和代碼。
線程通信比進(jìn)程通信簡單。
線程之間的上下文切換通常比進(jìn)程之間的切換便宜。
常見的錯(cuò)誤是使用 run() 而不是 start() 方法啟動(dòng)線程。
線程 myThread = new Thread(MyRunnable());
myThread.run(); //應(yīng)該是start();
您創(chuàng)建的線程不會(huì)調(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
通過上述介紹,相信大家對(duì)Java線程創(chuàng)建方式已經(jīng)有所了解,大家如果想了解更多相關(guān)知識(shí),不妨來關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java基礎(chǔ)教程技術(shù)文檔,里面還有更豐富的知識(shí)等著大家去學(xué)習(xí),相信對(duì)大家一定會(huì)有所幫助的。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743