java實現多線程的兩種方式
阿新 • • 發佈:2018-07-29
vat nts lock name div print 創建對象 pre thread
Java需要並發控制三個原因:
- 多線程環境
- 存在共享資源
- 多個線程操作(修改)共享資源
下面分別用繼承Thread類和實現Runnable接口倆種方式實現並發控制,
繼承Thread類
繼承Thread類方式,最後創建對象是因為會是三個不同的線程對象,所以需要將共享資源和鎖都靜態化,如果不這樣的話,就不存在共享資源一說了,自然也沒有並發控制的說法。
class MyThread extends Thread{ //電影票總數100張 private static int ticket=100; //鎖對象 private static Object obj = new Object(); @Overridepublic void run() { while(true){ synchronized (obj) { if(ticket>0){ System.out.println(this.currentThread().getName()+"正在出售第"+ticket--+"張票"); } } try { Thread.sleep(1000); }catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public class ThreadDemo { public static void main(String[] args) { Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3= new MyThread(); t1.setName("售票員1"); t2.setName("售票員2"); t3.setName("售票員3"); t1.start(); t2.start(); t3.start(); } }
實現Runnable接口
實現Runnable接口方式,因為構造函數中,需要傳入一個Runnable接口類型,所以這裏就直接存在共享資源了,靜態修飾可有可無,但是還是寫上比較好。
class MyRunnable implements Runnable{ //電影票總數100張 private int ticket=100; //鎖對象 private Object obj = new Object(); @Override public void run() { while(true){ synchronized (obj) { if(ticket>0){ System.out.println(Thread.currentThread().getName()+"正在出售第"+ticket--+"張票"); } } try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public class RunnableDemo { public static void main(String[] args) { Runnable r = new MyRunnable(); Thread t1 = new Thread(r,"售票員1"); Thread t2 = new Thread(r,"售票員2"); Thread t3 = new Thread(r,"售票員3"); t1.start(); t2.start(); t3.start(); } }
java實現多線程的兩種方式