java多線程中的實現方式存在兩種:
方式一:使用繼承方式
例如:
1 PersonTest extends Thread{ 2 3 String name; 4 5 public PersonTest(String name){ 6 7 super(name); 8 9 this.name=name 10 11 } 12 13 }
方式二:使用實現接口的方式
例如:
1 public PersonT implements Runnable{ 2 public void run(){ 3 //此處為執行的代碼 4 } 5 } 6 //實例化方式 7 public jacktest{ 8 public static void main(String[] args){ 9 PersonT t=new PersonT(); 10 Thread tt=new Thread(t,"線程1"); 11 tt.start(); 12 } 13 }
wait使用方式:
package TestThread.ThreadSynchronized.TestInterruptedException; public class InterruptDemo { public static void main(String[] args) { TestWait t = new TestWait("線程1"); TestWait t1 = new TestWait("線程2"); t.start(); t1.start(); } } class TestWait extends Thread { String name; public TestWait(String name) { super(name); this.name = name; } public synchronized void run() { for (int i = 0; i < 5; i++) { if (i == 4) { try { // 等待之后立即釋放當前鎖,並且進入等待池中等待喚醒 // 當等待池中的線程被喚醒后,再次執行此語句之后的語句 this.wait(); System.out.println(Thread.currentThread().getName() + ":我還沒有被執行到!"); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + ":當前的值為--->" + i); } } }