res/layou/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lai.class_bmi.MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textSize="20sp"
            android:text="@string/height"
            />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textSize="20sp"
            android:id="@+id/editText" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:text="@string/weight"
            android:layout_margin="10dp"
             />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textSize="20sp"
            android:id="@+id/editText2" />
    </LinearLayout>
    <!--android:onClick="onCaculate"是第五種方法-->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_gravity="center"
        android:onClick="onCaculate"
        android:id="@+id/button" />
</LinearLayout>

res/layou/activity_bmi.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@string/height"
            android:textSize="20sp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text=" "
            android:textSize="20sp"
            android:id="@+id/textView4" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@string/weight"
            android:textSize="20sp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:textSize="20sp"
            android:text=" "
            android:id="@+id/textView6" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="@string/BMI"
            android:textSize="20sp"
             />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text=" "
            android:textSize="20sp"
            android:id="@+id/textView8" />
    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="onBack"
        android:text="回上一頁"
        android:id="@+id/button2" />
</LinearLayout>

java/MainActivity

package com.lai.class_bmi;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    /* 先做第一個畫面的元件宣告 */
    EditText etHeight,etWeight;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* 載入畫面 */
        setContentView(R.layout.activity_main);

        findviews();
    }

    void findviews(){
        /* 第一個畫面 */
        etHeight=(EditText)findViewById(R.id.editText);
        etWeight=(EditText)findViewById(R.id.editText2);

    }
//    View.OnClickListener btnclick=new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//
//
//        }
//    };

                /*View一定要放 */
    public void onCaculate(View v){
        Intent intent=new Intent();
        /* 轉換畫面 intent.setClass(現在的畫面,要切換的畫面);  */
        intent.setClass(MainActivity.this,BmiActivity.class);
        /* 帶資料  */
        Bundle b=new Bundle();
        /* b.putString(名稱 , 要帶的值) */
        b.putString("h",etHeight.getText().toString());
        b.putString("w",etWeight.getText().toString());
        /* 將要帶的資料 b 用putExtras帶過去 */
        intent.putExtras(b);
        /* 啟用畫面 */
        startActivity(intent);



    }

    /* 隱含的方法  */
    void implicitActivity(){
//        Intent intent=new Intent();
//        intent.setAction("com.lai.bmi");
//        startActivity(intent);
    }
}

java/BmiActivity

package com.lai.class_bmi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.text.NumberFormat;

/**
 * Created by mingyilai on 2016/8/12.
 */

            /* 要先extends畫面 */
public class BmiActivity extends AppCompatActivity {
    Bundle b;//要帶的資料
    TextView tvHeight,tvWeight,tvBmi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* 載入BMI的畫面 */
        setContentView(R.layout.activity_bmi);

        /* 建立接收元件intent */
        Intent intent=getIntent();
        if(intent == null){
            return;
        }

        /* 接收資料 */
        b=intent.getExtras();
        /* 接收值 */
        b.getString("h","w");

        findviews();
        setdata(); //設定值
    }

    void findviews(){
        tvHeight = (TextView)findViewById(R.id.textView4);
        tvWeight = (TextView)findViewById(R.id.textView6);
        tvBmi = (TextView)findViewById(R.id.textView8);
    }

    void setdata(){
        tvHeight.setText(b.getString("h"));
        tvWeight.setText(b.getString("w"));
        //將接收的值轉換成數字
        double h=Double.parseDouble(b.getString("h"))/100;
        double w=Double.parseDouble(b.getString("w"));
        double bmi=w/(h*h);
        //先叫出NumberFormat的功能
        NumberFormat nf=NumberFormat.getInstance();
        //只取小數點後面2位
        nf.setMaximumFractionDigits(2);

        /* textview用 append串接字串 */
        tvBmi.setText(String.valueOf(nf.format(bmi)) + "\n");
        if(bmi >= 35) {
            tvBmi.append("重度肥胖");
        }else if(bmi < 35 && bmi >= 30){
            tvBmi.append("中度肥胖");
        }else if(bmi < 30 && bmi >= 27){
            tvBmi.append("輕度肥胖");
        }else if(bmi < 27 && bmi >= 24){
            tvBmi.append("過重");
        }else if(bmi < 24 && bmi >= 18.5){
            tvBmi.append("正常範圍");
        }else{
            tvBmi.append("體重過輕");
        }
    }



    public void onBack(View v){
//        /* Back stack */
//        Intent back=new Intent(BmiActivity.this,MainActivity.class);
//        /* 開新畫面 */
//        startActivity(back);

        /* 沒有Back stack */
        BmiActivity.this.finish();
    }
}

 

 

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()

res/layou/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/pic"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lai.class3_order.MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tableNumber"
            android:textSize="@dimen/BigText"
            android:textColor="@color/colorAccent"
            android:id="@+id/textView" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editText" />
    </LinearLayout>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_margin="20dp"
        android:orientation="horizontal">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/BigText"
            android:text="@string/normal"
            android:textColor="@color/colorAccent"
            android:id="@+id/radioButton" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="@dimen/BigText"
            android:textColor="@color/colorAccent"
            android:text="@string/vip"
            android:id="@+id/radioButton2" />
    </RadioGroup>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/meal"

        android:textSize="@dimen/BigText"
        android:layout_gravity="center_horizontal"
        android:id="@+id/textView2" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:gravity="center_horizontal"
        android:layout_margin="20dp"
        android:layout_height="wrap_content">

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/BigText"
            android:text="@string/ameal"
            android:id="@+id/checkBox" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorAccent"
            android:text="@string/bmeal"
            android:textSize="@dimen/BigText"
            android:id="@+id/checkBox2"
            android:checked="false" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:gravity="center_horizontal"
        android:layout_margin="20dp"
        android:layout_height="wrap_content">

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/BigText"
            android:text="@string/cmeal"
            android:id="@+id/checkBox3" />

        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/BigText"
            android:text="@string/dmeal"
            android:id="@+id/checkBox4" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/colorAccent"
        android:textSize="@dimen/BigText"
        android:text="@string/beverage"
        android:id="@+id/textView3" />

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/BigText"
            android:text="@string/tea"
            android:id="@+id/radioButton3" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/BigText"
            android:text="@string/coffee"
            android:id="@+id/radioButton4" />
    </RadioGroup>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="20dp"
        android:textColor="@color/colorAccent"
        android:textSize="@dimen/BigText"
        android:text="@string/submit"
        android:id="@+id/button" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textColor="@color/colorAccent"
        android:textSize="@dimen/BigText"
        android:text="@string/totalMoney"
        android:padding="20dp"
        android:id="@+id/textView4" />
</LinearLayout>

 

java/MainActivity

package com.lai.class3_order;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    EditText etTableNumber;
    RadioButton rbNormal,rbVip,rbTea,rbCoffee;
    CheckBox cbA,cbB,cbC,cbD;
    Button btn;
    TextView tvShow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findviews();
    }

    void findviews(){
        etTableNumber = (EditText)findViewById(R.id.editText);
        rbNormal = (RadioButton)findViewById(R.id.radioButton);
        rbVip = (RadioButton)findViewById(R.id.radioButton2);
        rbTea = (RadioButton)findViewById(R.id.radioButton3);
        rbCoffee = (RadioButton)findViewById(R.id.radioButton4);
        cbA = (CheckBox)findViewById(R.id.checkBox);
        cbA.setTag(100.0); //新增價錢的標籤
        cbB = (CheckBox)findViewById(R.id.checkBox2);
        cbB.setTag(150.0);
        cbC = (CheckBox)findViewById(R.id.checkBox3);
        cbC.setTag(200.0);
        cbD = (CheckBox)findViewById(R.id.checkBox4);
        cbD.setTag(250.0);
        btn = (Button)findViewById(R.id.button);
        tvShow = (TextView)findViewById(R.id.textView4);
        //設定監聽器
        btn.setOnClickListener(btnListener);

    }

    //建立監聽器
    View.OnClickListener btnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            double total=0.0;
            StringBuilder sb = new StringBuilder();
            sb.append("桌號").append(etTableNumber.getText().toString()).append("\n");
            if(rbNormal.isChecked()){
                sb.append(rbNormal.getText()).append("\n");
            }else{
                sb.append(rbVip.getText()).append("\n");
            }
            //主餐的目錄
            sb.append(getResources().getString(R.string.meal)).append("\n").append(" ");
            if(cbA.isChecked()){
                sb.append(cbA.getText()).append(" ");
                total+=(double)cbA.getTag();
            }
            if(cbB.isChecked()){
                sb.append(cbB.getText()).append(" ");
                total+=(double)cbB.getTag();
            }
            if(cbC.isChecked()){
                sb.append(cbC.getText()).append(" ");
                total+=(double)cbC.getTag();
            }
            if(cbD.isChecked()){
                sb.append(cbD.getText()).append(" ");
                total+=(double)cbD.getTag();
            }
            //附餐的目錄
            sb.append("\n").append(getResources().getString(R.string.beverage)).append("\n").append(" ");
            if(rbTea.isChecked()){
                sb.append(rbTea.getText()).append("\n");
            }else{
                sb.append(rbCoffee.getText()).append("\n");
            }

            if(rbVip.isChecked()){
                sb.append(getResources().getString(R.string.totalMoney)).append(total*0.9).append(getResources()).append(getString(R.string.dollar));
            }else{
                sb.append(getResources().getString(R.string.totalMoney)).append(total).append(getResources()).append(getString(R.string.dollar));

            }

            tvShow.setText(sb);

        }
    };
}
文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()

package net.macdidi.class1_exchange;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    EditText etInput;
    TextView tvShow;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findviews();
    }
    void findviews(){
        etInput=(EditText)findViewById(R.id.editText);
        tvShow=(TextView)findViewById(R.id.textView3);
        //1.建立元件
        btn=(Button)findViewById(R.id.button);
        //3.註冊監聽器
        btn.setOnClickListener(btnListener);

        //第三種
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

        //第四種
//        btn.setOnClickListener(this);



    }

    //2.建立監聽器(匿名內部類)最常用的一種
    View.OnClickListener btnListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            double usd=0;
            String strUsd=etInput.getText().toString();
            try {
                usd = Double.parseDouble(strUsd);
            }catch(NumberFormatException e){
                e.printStackTrace();
                Toast.makeText(MainActivity.this,"輸入數字格式不正確", Toast.LENGTH_SHORT).show();
                //(this指所在類別的物件,要顯示的文字,出現時間)
            }
            double twd=usd*30.0;
            tvShow.setText(String.valueOf(twd));
        }
    };

    @Override
    public void onClick(View v) {

    }

    //配合第四種
//    @Override
//    public void onClick(View v) {
//
//    }


    //第二種
//    class BtnClick implements View.OnClickListener{
//
//        @Override
//        public void onClick(View v) {
//
//        }
//    };
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="net.macdidi.class1_exchange.MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="160dp"
            android:layout_height="wrap_content"
            android:text="@string/USD"
            android:textColor="@color/blue"
            android:textSize="@dimen/BigText"
            android:id="@+id/textView" />

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/input"
            android:id="@+id/editText" />
    </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/TWD"
            android:textColor="#aa3700ff"
            android:textSize="@dimen/BigText"
            android:id="@+id/textView2" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" "
            android:id="@+id/textView3" />
    </LinearLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/exchange"
        android:textSize="30sp"
        android:id="@+id/button" />

</LinearLayout>

 

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()


package pkg13.pkg50;

import java.util.Properties;


public class Main {

    public static void main(String[] args) {
        Properties pro = new Properties();      //建立Properties物件
        pro.setProperty("BJ", "BeiJing");       //設定內容 
        pro.setProperty("times", "60");
        
        System.out.println("BJ 的屬性值為" + pro.getProperty("BJ"));
        System.out.println("time的屬性值為" + pro.getProperty("times"));
    }
    
}
 


run:
BJ 的屬性值為BeiJing
time的屬性值為60
BUILD SUCCESSFUL (total time: 0 seconds)
 


 

 

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()


package pkg13.pkg26;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class Main {
    public static void main(String[] args) {
        Map<String, String> map = null;         //宣告Map物件
        map = new HashMap<String, String>();        //key和value是string類別
        //增加內容 
        map.put("Gjun", "巨匠電腦");
        map.put("Google", "http://www.google.com");
        map.put("Yahoo", "http://www.yahoo.com.tw");
        map.put("Pcschool", "http://www.pcschool.com.tw");
        
        String val = map.get("Gjun");       //根據key求出value
        System.out.println("val = " + val);
        
        //將map的key值全部列出
        //先宣告一個Set來接收key
        Set<String> keys = map.keySet();
        //利用Iterator介面,將集合內容輸出
        //產生key的Iterator介面實體
        Iterator <String> iter = keys.iterator();
        //hasNext判斷有值時,列出值
        while(iter.hasNext()){
            String str = iter.next();
            System.out.print(str + "  ");
            System.out.println(map.get(str));
        }
    }
}
 


run:
val = 巨匠電腦
Google  http://www.google.com
Yahoo  http://www.yahoo.com.tw
Gjun  巨匠電腦
Pcschool  http://www.pcschool.com.tw
BUILD SUCCESSFUL (total time: 0 seconds)
 

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()

 allSet.add("aa");
        allSet.add("aa");
        allSet.add("bb");


run:
[aa, bb, cc, dd]
[aa, bb, cc, dd]
BUILD SUCCESSFUL (total time: 0 seconds)
 

mingyilai 發表在 痞客邦 留言(0) 人氣()


package pkg13.pkg1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        //定義一個List物件
        List<String> allList = null;            //父類別
        Collection<String> allCollection = null;
        
        allList = new ArrayList<String>();          //子類別
        allCollection = new ArrayList<String>();  //向上轉型
         
        //新增資料
        allList.add("Hello");
        allList.add("Tom");
        allList.add("May");
        //指定位置插入
        allList.add(1,"John");
        
        //刪除資料
        allList.remove(0);
        allList.remove("Tom");
        System.out.println(allList);
        
        allCollection.add("AA");
        allCollection.add("BB");
        allCollection.add("CC");
        //指定位置插入
        allList.addAll(1,allCollection);        //此處為向上轉型,所以無法執行子類別的方法
        System.out.println(allCollection);
        System.out.println(allList);
        allList.removeAll(allCollection);
        System.out.println(allList);
    }
}
 


run:
[John, May]
[AA, BB, CC]
[John, AA, BB, CC, May]
[John, May]
BUILD SUCCESSFUL (total time: 0 seconds)
 

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()

一個多執行緒的程式如果是透過Runnable介面實現的,則表示類別中的屬性將被多個執行緒共用


package pkg9.pkg19;

class MyThread implements Runnable{
    private int ticket = 5;
    public void run(){
        for(int i = 0 ; i < 100 ; i++){
            if(ticket > 0){
                try{
                Thread.sleep(1000);
                }catch(InterruptedException ex){}
                System.out.println("賣票 目前有" + ticket-- + "票");
                
            }
        }
    }
}
public class Main {

    public static void main(String[] args) {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        Thread t3 = new Thread(mt);
        t1.start();
        t2.start();
        t3.start();
    }
}
 


run:
賣票 目前有4票
賣票 目前有3票
賣票 目前有5票
賣票 目前有2票
賣票 目前有1票
賣票 目前有1票
賣票 目前有0票
BUILD SUCCESSFUL (total time: 3 seconds)

 


同步就是指多個操作在同一個時間段內只能有一個執行緒執行,其他執行緒要等待此執行緒完成之後才可以繼續執行。


package pkg9.pkg19;

class MyThread implements Runnable {

    private int ticket = 5;

    public void run() {
        for (int i = 0; i < 100; i++) {
            //同步程式碼區塊
            synchronized (this) {
                if (ticket > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                    }
                    System.out.println("賣票 目前有" + ticket-- + "票");
                }
            }
        }
    }
}

public class Main {

    public static void main(String[] args) {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        Thread t3 = new Thread(mt);
        t1.start();
        t2.start();
        t3.start();
    }
}
 


run:
賣票 目前有5票
賣票 目前有4票
賣票 目前有3票
賣票 目前有2票
賣票 目前有1票
BUILD SUCCESSFUL (total time: 5 seconds)
 

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()


package pkg9.pkg8;

import com.sun.istack.internal.logging.Logger;
import java.util.logging.Level;

class MyThread implements Runnable{
    public void run(){
        for(int i = 0 ; i < 5 ; i++){
            System.out.println(Thread.currentThread().getName() + "i = " + i);
            //執行禮讓
            if( i == 3){
                System.out.println("讓");
                Thread.currentThread().yield();  //執行緒禮讓
            }
        }
    }
}
public class Main {

    public static void main(String[] args) {
        MyThread my = new MyThread();       //產生實體物件
        Thread t1 = new Thread(new MyThread(),"執行緒-A");       //產生實體Thread物件
        Thread t2 = new Thread(new MyThread(),"執行緒-B"); 
        Thread t3 = new Thread(new MyThread(),"執行緒-C"); 
        //設定執行的優先順序
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.NORM_PRIORITY);
        t3.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }
}
 


run:
執行緒-Ai = 0
執行緒-Ai = 1
執行緒-Ai = 2
執行緒-Ai = 3

執行緒-Bi = 0
執行緒-Ci = 0
執行緒-Ci = 1
執行緒-Ci = 2
執行緒-Ci = 3

執行緒-Bi = 1
執行緒-Bi = 2
執行緒-Bi = 3

執行緒-Ai = 4
執行緒-Ci = 4
執行緒-Bi = 4
BUILD SUCCESSFUL (total time: 0 seconds)
 

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()


package pkg9.pkg8;

import com.sun.istack.internal.logging.Logger;
import java.util.logging.Level;

class MyThread implements Runnable{
    public void run(){
        for(int i = 0 ; i < 3 ; i++){
            try{
                Thread.sleep(1000);
            }catch(Exception e){}
            System.out.println(Thread.currentThread().getName() + "i = " + i);
        }
    }
}
public class Main {

    public static void main(String[] args) {
        MyThread my = new MyThread();       //產生實體物件
        Thread t1 = new Thread(new MyThread(),"執行緒-A");       //產生實體Thread物件
        Thread t2 = new Thread(new MyThread(),"執行緒-B"); 
        Thread t3 = new Thread(new MyThread(),"執行緒-C"); 
        //設定執行的優先順序
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.NORM_PRIORITY);
        t3.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }
}
 


run:
執行緒-Ai = 0
執行緒-Bi = 0
執行緒-Ci = 0
執行緒-Ai = 1
執行緒-Ci = 1
執行緒-Bi = 1
執行緒-Ai = 2
執行緒-Bi = 2
執行緒-Ci = 2
BUILD SUCCESSFUL (total time: 3 seconds)
 


並非執行緒的優先順序越高就一定會先執行,哪個執行緒先執行將由CPU的排程決定。主方法的優先順序是NORM_PRIORITY

文章標籤

mingyilai 發表在 痞客邦 留言(0) 人氣()