標籤:pre class show null 封裝 eth div bool code
1、建立多線程方式繼承Thread類
class ThreadDemo1{ public static void main(String args[]){ Demo1 d1 = new Demo1(); d1.start(); Demo1 d2 = new Demo1(); d2.start(); }}class Demo1 extends Thread{ public void run(){ show(); } public void show(){ while(true){ try{Thread.sleep(3000); }catch(InterruptedException e){ } System.out.println("ол╣Щ"+Thread.currentThread().getName()); } }}
2、實現多線程第二種方式Runnable介面
class ThreadDemo2{ public static void main(String[]args){ Demo d1 = new Demo(); Thread t1 = new Thread(d1); Thread t2 = new Thread(d1); Thread t3 = new Thread(d1); Thread t4 = new Thread(d1); t1.start(); t2.start(); t3.start(); t4.start(); }}class Demo implements Runnable{ private int sum; public void show(){ for(int x=0;x<20;x++){ synchronized(this){ sum+=100; System.out.println(Thread.currentThread().getName()+"銀行金庫即時金額:"+sum); } } } public void run(){ show(); }}
3、多線程中的同步代碼塊、同步函數、靜態同步函數需要注意的事項
當函數名用static修飾時,同步鎖不能用this,static函數的鎖使用對象.getClass()擷取的位元組碼檔案或者類名.class擷取;
class ThreadDemo3{ public static void main(String[]args){ Demo d1= new Demo(); Thread t1 = new Thread(d1); Thread t2 = new Thread(d1); Thread t3 = new Thread(d1); Thread t4 = new Thread(d1); t1.start(); t2.start(); try{Thread.sleep(10);}catch(InterruptedException e){} Demo.flag=false; t3.start(); t4.start(); }}/*new Thread(d1);任務封裝後在Thread類裡面的傳遞過程class Thread1 implements Runnable{ Runnable r1; Thread1(Runnable r1){ this.r1=r1; } public void run(){ if(r1!=null) r1.run(); } public void start(){ run(); }}*/class Demo implements Runnable{ public static boolean flag=true; private static int num=300; public void run(){ if(flag){ while(true) method(); }else{ synchronized(Demo.class){ while(true) if(num>0){ try{Thread.sleep(30);}catch(InterruptedException e){} System.out.println("同步代碼塊售票口:"+Thread.currentThread().getName()+"已售出萬達電影院門票號:"+num--); } } } } public synchronized static void method(){ if(num>0){ try{Thread.sleep(30);}catch(InterruptedException e){} System.out.println("同步函數售票口:"+Thread.currentThread().getName()+"已售出萬達電影院門票號:"+num--); } }}
java練習多線程