2013年2月10日日曜日

[Java]子スレッドの終了を待つ

join メソッドを使って子スレッドの終了を待つ。














メインスレッドは子スレッドの処理が完了するまで待ち、子スレッドの完了を受けてから End of main を出力する。
Example: java_thread_01.java

public class java_thread_01 extends Thread {
    public static void main(String args[]) {
        System.out.println("Start of main");

        /* 子スレッド生成、スタート */
        java_thread_01 thread = new java_thread_01("Child Thread");
        thread.start();

        /* 子スレッドの終了を待つ */
        try {
            thread.join();
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("End of main");
    }

    /* 子スレッドの初期化 */
    public java_thread_01(String name) {
        super(name);
    }

    public void run() {
        /* 子スレッドの処理 */
        int i;
        for (i = 0; i < 5; i++) {
            System.out.println(this.getName() + ": " + i);
            try {
                sleep(500); // 500msec 停止
            }
            catch (InterruptedException e) {

            }
        }
        System.out.println(this.getName() + ": End");
    }
}
実行結果
> javac java_thread_01.java
> java java_thread_01
Start of main
Child Thread: 0
Child Thread: 1
Child Thread: 2
Child Thread: 3
Child Thread: 4
Child Thread: End
End of main

[Java]マルチスレッド

Thrad クラスを継承してマルチスレッドを扱うクラスを作る










Example: java_thread_00.java
/* マルチスレッド */
public class java_thread_00 extends Thread {
    public java_thread_00(String name) {
        super(name);
    }

    public static void main(String[] args) {
        /* スレッドオブジェクトのインスタンス生成 */
        java_thread_00 thread0 = new java_thread_00("Thread 0");
        java_thread_00 thread1 = new java_thread_00("Thread 1");

        /* スレッドを開始 */
        thread0.start();
        thread1.start();

        System.out.println("End of main");
    }

    public void run() {
        int i;
        for (i = 0; i < 10; i++) {
            System.out.println(this.getName() + " : " + i);
            try {
                /* 500msec スレッド停止 */
                sleep(500);
            }
            catch (InterruptedException e) {

            }
        }
    }
}
実行結果
> javac java_thread_00.java
> java java_thread_00
End of main
Thread 0 : 0
Thread 1 : 0
Thread 1 : 1
Thread 0 : 1
Thread 0 : 2
Thread 1 : 2
Thread 0 : 3
Thread 1 : 3
Thread 1 : 4
Thread 0 : 4
Thread 1 : 5
Thread 0 : 5
Thread 0 : 6
Thread 1 : 6
Thread 0 : 7
Thread 1 : 7
Thread 1 : 8
Thread 0 : 8
Thread 1 : 9
Thread 0 : 9

[Java]Network Interface の一覧を表示する

NetworkInterface クラスの getNetworkInterfaces メソッドで Network Interface の一覧が取得できる
Example: java_net_04.java
// ネットワーク I/F を表示する
import java.net.*;
import java.util.Enumeration;

public class java_net_04 {
        public static void main(String[] args) {
                try {
                        // Network Interface のリスト
                        Enumeration enuIfs = NetworkInterface.getNetworkInterfaces();
                        while (enuIfs.hasMoreElements()) {
                                NetworkInterface ni = (NetworkInterface)enuIfs.nextElement();
                                System.out.println("Names: " + ni.getName() + " / " + ni.getDisplayName());
                                byte hwAddr[] = ni.getHardwareAddress();
                                if (hwAddr != null) {
                                        System.out.print("     MAC address: ");
                                        for (byte segment: hwAddr) {
                                                System.out.printf("%02x ", segment);
                                        }
                                        System.out.println();
                                }

                                Enumeration ipaddrs = ni.getInetAddresses();
                                while (ipaddrs.hasMoreElements()) {
                                        InetAddress address = (InetAddress)ipaddrs.nextElement();
                                        System.out.println("     Address: " + address.getHostAddress());
                                }
                        }
                }
                catch (Exception e) {
                        System.err.println(e);
                        return;
                }
        }
}
実行結果
> javac java_net_04.java
> java java_net_04
Names: lo / MS TCP Loopback interface
     Address: 127.0.0.1
Names: eth0 / VMware Virtual Ethernet Adapter for VMnet8
     MAC address: xx xx xx xx xx xx
     Address: 192.168.153.1
Names: eth1 / VMware Virtual Ethernet Adapter for VMnet1
     MAC address: xx xx xx xx xx xx
     Address: 192.168.247.1
Names: eth2 / Intel(R) 82566DM-2 Gigabit Network Connection - ?p?P?b?g ?X?P?W
     MAC address: xx xx xx xx xx xx
     Address: 192.168.1.1

[Java]ネットワーク経由でのデータの取得

URL クラスの openStream メソッドでデータを取得する
Proxy サーバを指定する場合は System.setProperty で各プロパティ値を設定する
Example: java_net_03.java
// データを取得する
import java.net.*;
import java.io.*;

public class java_net_03 {
        public static void main(String[] args) {
                try {
                        // Proxy の設定
                        System.setProperty("proxySet", "true");
                        System.setProperty("proxyHost", "myproxy.mydomain");
                        System.setProperty("proxyPort", "8080");

                        URL url = new URL(args[0]);
                        FileOutputStream out = new FileOutputStream(args[1]);
                        InputStream input = url.openStream();
                        while (true) {
                                int read = input.read();
                                if (read == -1) {
                                        break;
                                }
                                out.write(read);
                        }
                        out.close();
                }
                catch (Exception e) {
                        System.err.println(e);
                        return;
                }
        }
}
実行結果
> javac java_net_03.java
> java java_net_03 http://www.google.co.jp/intl/ja_jp/images/logo.gif logo.gif
実行したディレクトリに logo.gif というファイルが生成される

[Java]URL 成分の分解

URL クラスの getProtocol, getHost, getPort, getFile, getRef メソッドを使用して、URL の各成分を分解することができる
Example: java_net_02.java
// URL を各要素に分解
import java.net.*;

public class java_net_02 {
        public static void main(String[] args) {
                try {
                        URL url = new URL(args[0]);
                        System.out.println("Schema   : " + url.getProtocol());
                        System.out.println("Host     : " + url.getHost());
                        System.out.println("Port     : " + url.getPort());
                        System.out.println("Path     : " + url.getFile());
                        System.out.println("Reference: " + url.getRef());
                }
                catch (Exception e) {
                        System.err.println(e);
                        return;
                }
        }
}
実行結果
> javac java_net_02.java
> java java_net_02 http://localhost:80/new.html#hoge
Schema   : http
Host     : localhost
Port     : 80
Path     : /new.html
Reference: hoge

[Java]InetAddress クラス

Java のネットワークプログラムを作成するにあたり、ホストの情報を格納するクラス InetAddress クラスがある。

getByName
getByName メソッドで InetAddress クラスを取得し、取得後に getHostName, getHostAddress メソッドでホスト名や IP アドレスを取得することができる。
Example: java_net_00.java
import java.net.*;

public class java_net_00 {
    public static void main(String[] args) {
        InetAddress host = null;
        try {
            host = InetAddress.getByName(args[0]);
        }
        catch (UnknownHostException e) {
            System.out.println("Not found " + args[0]);
            return;
        }
        System.out.println("Host name = " + host.getHostName());
        System.out.println("IP = " + host.getHostAddress());
    }
}

実行結果
> javac java_net_00.java
> java java_net_00 www.google.com
Host name = www.google.com
IP = 66.249.89.147

getLocalHost
ローカルホストの情報を取得する場合は getLocalHost メソッドを使用する
Example: java_net_01.java
import java.net.*;

public class java_net_01 {
    public static void main(String[] args) {
        InetAddress host = null;
        try {
            host = InetAddress.getLocalHost();
        }
        catch (UnknownHostException e) {
            System.err.println(e);
            return;
        }
        System.out.println(host);
    }
}

実行結果
> javac java_net_01.java
> java java_net_01
my-windows-pc/192.168.0.1

[Java]ファイル入出力

ファイル読み込み
FileReader, BufferedReader クラスを使ってファイルの読み込みを行う
Example: java_file_00.java
/* ファイル読み込み */
import java.io.*;

public class java_file_00 {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Input file name");
            System.exit(1);
        }

        try {
            FileReader fr = new FileReader(args[0]);
            BufferedReader br = new BufferedReader(fr);

            String str;
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
            br.close();
            System.out.println("------------------ End");
        }
        catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error");
            System.exit(1);
        }
    }
}
実行結果
> javac java_file_00.java
> java java_file_00 java_file_00.java
/* ファイル読み込み */
import java.io.*;

public class java_file_00 {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Input file name");
            System.exit(1);
        }

        try {
            FileReader fr = new FileReader(args[0]);
            BufferedReader br = new BufferedReader(fr);

            String str;
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
            br.close();
            System.out.println("------------------ End");
        }
        catch (IOException e) {
            e.printStackTrace();
            System.out.println("Error");
            System.exit(1);
        }
    }
}
------------------ End

ファイル書き込み
FileOutputStream, OutputStreamWriter, BufferedWriter クラスを使ってファイルへの書き込みを行う
Example: java_file_01.java
/* ファイル書き込み */
import java.io.*;

public class java_file_01 {
    public static void main(String[] args) {
        try {
            FileOutputStream fos = new FileOutputStream("test.txt");
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            BufferedWriter bw = new BufferedWriter(osw);
            String str = "Hello, world\n";
            bw.write(str);
            str = "日本語入力はできますか?\n";
            bw.write(str);

            bw.close();
            osw.close();
            fos.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
ソースコードのエンコードを UTF-8 にする場合はコンパイル時に -encoding UTF-8 オプションをつけないと日本語文字列の処理に失敗してしまう

実行結果
> javac -encoding UTF-8 java_file_01.java
> java java_file_01
test.txt は UTF-8 で以下のように書き込まれる
Hello, world
日本語入力はできますか?