您好,登錄后才能下訂單哦!
這篇文章主要介紹“java中有哪些創(chuàng)建線程的方法”,在日常操作中,相信很多人在java中有哪些創(chuàng)建線程的方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”java中有哪些創(chuàng)建線程的方法”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
public class ExtendsThreadTest extends Thread { @Override public void run() { System.out.println("thread is running!"); } public static void main(String[] args) { ExtendsThreadTest et1 = new ExtendsThreadTest(); et1.start(); } }
public class RunnableTest implements Runnable{ @Override public void run() { System.out.println("thread is running!"); } public static void main(String[] args) { Thread t1 = new Thread(new RunnableTest()); t1.start(); } }
public class App { public static void main(String[] args){ new Thread(new Runnable() { @Override public void run() { System.out.println("thread1 is running!"); } }){}.start(); new Thread(){ @Override public void run(){ System.out.println("thread2 is running!"); } }.start(); } }
public class CallableTest { public static void main(String[] args) throws Exception { Callable<Integer> call = new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("thread is running!"); return 1; } }; FutureTask<Integer> task = new FutureTask<>(call); Thread t = new Thread(task); t.start(); } }
public class TimerTest { public static void main(String[] args) throws Exception { Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("thread is running!"); } }, new Date()); } }
public class ThreadPoolTest { public static void main(String[] args) { // 創(chuàng)建線程池 ExecutorService threadPool = Executors.newFixedThreadPool(10); while(true) { threadPool.execute(new Runnable() { // 提交多個線程任務,并執(zhí)行 @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running .."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } } }
到此,關于“java中有哪些創(chuàng)建線程的方法”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。