java中實現多線程的幾種方式(簡單實現)


一、以下只是簡單的實現多線程

1:繼承Thread

2:實現 Runnable

3:實現callable

如果需要返回值使用callable,如果不需要返回最好使用runnable,因為繼承只能單繼承,所以不推薦使用Thread。

具體代碼

@RunWith(SpringRunner.class)
@SpringBootTest
public class Thread_Test {

private class Thread1 extends Thread{
@Override
public void run() {
super.run();
System.out.println("執行了Thread的Run方法");
}
}

private class Thread2 implements Runnable{
@Override
public void run() {
System.out.println("執行了Runnable的Run方法");
}
}

private class Thread3 implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("執行了Runnable的Run方法");
Thread.sleep(5000);    //讓線程休眠5s,測試返回值
return "I am callable";
}
}

@Test
public void testThread() throws Exception{
Thread1 t1 = new Thread1();
new Thread(t1).start();

Thread2 t2 = new Thread2();
new Thread(t2).start();

Thread3 t3 = new Thread3();
FutureTask<String> task = new FutureTask<String>(t3);
new Thread(task).start();
System.out.println(task.get());          //是異步獲取的值,等待程序執行完
}
}

執行結果

 

 二、停止線程的方法

suspend()、resume()、stop() ,不建議使用,這種是強制關閉線程,如果有鎖可能不會釋放。

建議使用interrupt()方法停止線程。

interrupt:中斷一個線程。不是強行的中斷,只是添加了一個中斷標志位true。

interrupted:判定當前線程是否處於中斷狀態。

static的 isInterrupted:判定當前線程是否處於中斷狀態。他會把中斷的標志位給位false。

代碼:public class EndThread {


private static class UseThread extends Thread{
@Override
public void run() {
String name = Thread.currentThread().getName();
while(!isInterrupted()){  //當中斷標識位位true,就跳出循環。
System.out.println(name+"is run");
}
       System.out.println(name + "is flag "+isInterrupted()); //當前的標識位為true
       interrupted(); //interrupted把中斷標識位設置為false。
       System.out.println(name + "is flag "+isInterrupted()); //當前的標識位為false
      }
  }
 public static void main(String[] args) throws Exception {
Thread u = new UseThread();
u.start();
Thread.sleep(1000);
u.interrupt(); //告訴程序要中斷了,設置中斷標志位。
}
}

運行結果

  Thread-0is run
  Thread-0is run
  Thread-0is flag true
  Thread-0is flag false



 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM