2015年9月13日 星期日

JAVA SL-275_0913

/*
‧使用 finally
無論 try 區塊中有無發生例外,若撰寫有 finally 區塊,則 finally 區塊一定會執行,如果程式撰寫的流程中先 return 了,而且也有寫 finally 區塊,那 finally 區塊會先執行完後,再將值傳回。

try{
do something…
}catch{
do something…
}finally{ // Always 會執行,且優先過 try-cache
….
}

可以允許的程式寫法:
try-cache
try-finally
try-cache-finally

錯誤的寫法:
catch finally
*/
/******************************************************************************/
public class FinallyDemo{
public static int test(boolean flag){
try{
if(flag){
return 1;
}
}finally{
System.out.println("finally...");
}
return 0;
}
public static void main(String args[]){
System.out.println(test(true));
}
}
/******************************************************************************/

/*
java.lang.AutoCloseable 介面
JDK 7 新增了自動關閉資源語法可用的套件,必須實作 java.lang.AutoCloseable 介面,其僅定義了 close() 方法
package java.lang.*;

public interface AutoCloseable{
void close() throws Exception;
}
*/

/*
執行序流程圖

---

執行序的執行狀態:
起始狀態
Thread t = new Thread();

可執行狀態
Thread t = new Thread();
t.start(); t.yield();

執行狀態
實作 Runnable 介面
繼承 Thread 類別
public void run(){
……
}

非可執行狀態
Thread t - new Thread();
sleep().wait().suspend();

結束狀態
stop()
正常結束

*/
/******************************************************************************/
// Thread

public class ThreadDemo{
public static void main(String args[]){
System.out.println("Hello Java 測試");
String str = Thread.currentThread().getName();
System.out.println("Thread name: " + str);
System.out.println(Thread.activeCount());
}
}

/******************************************************************************/
// 練習 Thread 寫龜兔賽跑
// TortoisHareDemo.java

public class TortoisHareDemo{
public static void main(String args [])throws InterruptedException{
boolean flags[]={true,false};
int totalStep=10;
int tortoiseStep=0;
int hareStep=0;
System.out.println("龜兔賽跑開始…");
while(tortoiseStep < totalStep && hareStep <totalStep){
Thread.sleep(1000);
tortoiseStep++;
System.out.printf("烏龜跑了 %d 步…%n", tortoiseStep);
boolean isHareSleep=flags[((int)(Math.random()*10))%2];
if(isHareSleep){
System.out.println("兔子睡著了…zzz");
}else{
hareStep+=2;
System.out.printf("兔子跑了 %d 步…%n", hareStep);
}
}
}
}
/******************************************************************************/
// 練習 Thread 寫龜兔賽跑,拆開來寫成三個檔案:
// Hare.java

public class Hare implements Runnable{
private boolean[] flags = {true,false};
private int totalStep;
private int step;
public Hare(int totalStep){
this.totalStep=totalStep;
}
public void run(){
try{
while(step<totalStep){
Thread.sleep(1000);
boolean isHareSleep = flags[((int)(Math.random()*10))%2];
if(isHareSleep){
System.out.println("兔子睡著了...");
}
else{
step +=2;
System.out.printf("兔子跑了 %d 步…%n", step);
}
}
}catch(InterruptedException ex){
throw new RuntimeException(ex);
}
}
}
//------------------------------------------------------------------------------------
//Tortoise.java

public class Tortoise implements Runnable{
private int totalStep;
private int step;
public Tortoise(int totalStep){
this.totalStep=totalStep;
}
public void run(){
try{
while(step<totalStep){
Thread.sleep(1000);
step++;
System.out.printf("烏龜跑了 %d 步 %n", step);
}
}catch(InterruptedException ex){
throw new RuntimeException(ex);
}
}
}
//------------------------------------------------------------------------------------
//TortoiseHareRace.java

public class TortoiseHareRace{
public static void main(String args[]){
Tortoise t = new Tortoise(10);
Hare h = new Hare(10);
Thread tortoiseThread = new Thread(t);
Thread hareThread = new Thread(h);
tortoiseThread.start();
hareThread.start();
}
}
/******************************************************************************/
// 實作 Thread 類別

class HelloThread extends Thread{
HelloThread(String str){
super(str);
}
public void run(){
for(int i=0;i<1000;i++){
String s = Thread.currentThread().getName();
System.out.println(s +" : " + i);
}
}
}
public class TestThread{
public static void main(String args[]){
HelloThread h =new HelloThread("Monic");
h.start();
}
}

/*
實作 Runnable 介面,好處是有彈性,還有機會繼承其它類別
 繼承 Thread 類別,通常是為了直接利用 Thread 類別中的一些方法才會直接繼承 Thread 類別
*/
/******************************************************************************/
/*
執行序有其優先權,可用 Thread 類別底下的 setPriority() 方法設定優先權,可設定值為 1~10,預設是 5 如果超出 1~10 以外的設定值會拋出 IllegalArgnmentException,數字越大優先權愈高,越優先排入;cpu 若相同,則輪流執行。
*/

// PersonDemo.java
class Person extends Thread{
Person(String str){
super(str);
}
public void run(){
String name=Thread.currentThread().getName();
int priority = Thread.currentThread().getPriority();
Thread.State state = Thread.currentThread().getState();
System.out.println( name + "優先序─ " + priority + ",狀態─ " + state);
for(int i=1;i<=10;i++){
System.out.println(name + "跑完第" + i + "圈");
if(name.equals("Ken") && i%3==0 ){
System.out.println(name + "休息 1 秒…");
}
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
}
public class PersonDemo{
public static void main(String args[]){
Person p1 = new Person("Ron");
Person p2 = new Person("Ken");
p1.start();
p2.start();
System.out.println("正在執行的執行序:" + Thread.activeCount());
}
}


/******************************************************************************/
/*
有幾種狀況會讓執行序進入 Blocked 狀態:
呼叫 Thread.sleep() 方法
進入 synchronized 前競爭物件鎖定的阻斷
呼叫 wait() 的阻斷
等待 input/output 完成

一個進入 Blocked 狀態的執行序可由另一個執行序呼叫該執行序的 interrupt() 方法,讓它離開 Blocked 狀態。
*/
/******************************************************************************/
// 比較 synchronized  同步

// 無同步
class Company{
static int sum=0;
static void add(int n){
int tmp=sum;
tmp+=n;
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
sum=tmp;
String name=Thread.currentThread().getName();
System.out.println("執行緒:" + name + ",存款為:" + sum);
}
}
class Ccompany extends Thread{
Ccompany(String str){
super(str);
}
public void run(){
for(int i=1;i<=3;i++)
Company.add(100);
}
}

public class SynchronizedDemo{
public static void main(String args[]){
Ccompany c1 = new Ccompany("Ron");
Ccompany c2 = new Ccompany("Ken");
c1.start();
c2.start();
}
}
/*
輸出結果:
*/
//----------------------------------------------------------------------------
// 加入同步
class Company{
static int sum=0;
synchronized static void add(int n){
int tmp=sum;
tmp+=n;
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
sum=tmp;
String name=Thread.currentThread().getName();
System.out.println("執行緒:" + name + ",存款為:" + sum);
}
}
class Ccompany extends Thread{
Ccompany(String str){
super(str);
}
public void run(){
for(int i=1;i<=3;i++)
Company.add(100);
}
}

public class SynchronizedDemo{
public static void main(String args[]){
Ccompany c1 = new Ccompany("Ron");
Ccompany c2 = new Ccompany("Ken");
c1.start();
c2.start();
}
}

/*
輸出結果:
*/
/******************************************************************************/
//wait

class Company{
static int sale = 0;
synchronized static void add(int n){
String name = Thread.currentThread().getName();
int sum = sale;
sum = sum + n;
System.out.println(name + "銷售量" + n + ",公司銷售量:" + sum);
sale=sum;
}
}
class Ccompany extends Company implements Runnable{
private String id;
public Ccompany(String id){
this.id=id;
}
public void run(){
for(int i=1;i<=10;i++){
Company.add(i);
if(sale > 5){
System.out.println("庫存量超過 5,停止生產…");
try{
wait();
}catch(InterruptedException e){
System.out.println("繼續生產...");
}
}
}
}
}

public class WaitDemo{
public static void main(String args[]){
Thread s1 = new Thread(new Ccompany("S 分店"),"C 分店");
Thread s2 = new Thread(new Ccompany("S2 分店"),"C2 分店");
s1.start();
s2.start();
//s2.interrupt();
}
}


沒有留言:

張貼留言