線程和進程的關係: 一個進程有N個線程java
一、實現線程的三種方式:ide
(1)繼承thread 類測試
[1]建立一個繼承thread類的類spa
package Thread01; public class MyThread extends Thread { private int i; @Override public void run() { for (; i < 10; i++) { System.out.println(getName()+"\t"+i); } } }
[2]建立測試類線程
package Thread01; public class MyTest { public static void main(String[] args) { for (int i = 0; i <10; i++) { System.out.println(Thread.currentThread().getName()+"\t"+i+"======"); if(i==5){ MyThread mt2 =new MyThread(); MyThread mt =new MyThread(); mt2.start(); mt.start(); } } } public static long getMemory() { return Runtime.getRuntime().freeMemory(); } }
(2)實現runnable 接口code
【1】 實現runnable 接口的類並非一個線程類,而是線程類的一個target ,能夠爲線程類構造方法提供參數來實現線程的開啓blog
package Thread02; public class SecondThread implements Runnable{ private int i; public void run() { for (; i < 20; i++) { System.out.println(Thread.currentThread().getName()+" "+i); if(i==20) { System.out.println(Thread.currentThread().getName()+"執行完畢"); } } } }
【2】測試類繼承
package Thread02; public class MyTest { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()+" "+i); if(i==5) { SecondThread s1=new SecondThread(); Thread t1=new Thread(s1,"線程1"); Thread t2=new Thread(s1,"線程2"); t1.start(); t2.start(); } } } }
(3)實現callable 接口接口
【1】建立callable 實現類進程
package Thread03; import java.util.concurrent.Callable; public class Target implements Callable<Integer> { int i=0; public Integer call() throws Exception { for (; i < 20; i++) { System.out.println(Thread.currentThread().getName()+""+i); } return i; } }
【2】測試類
package Thread03; import java.util.concurrent.FutureTask; public class ThirdThread { public static void main(String[] args) { Target t1=new Target(); FutureTask<Integer> ft=new FutureTask<Integer>(t1); Thread t2=new Thread(ft,"新線程"); t2.start(); try { System.out.println(ft.get()); } catch (Exception e) { // TODO: handle exception } } }