- public class ThreadName01 {
- public static void main(String[] args) {
- Thread th = Thread.currentThread();
- System.out.println("Thread Name = " + th.getName());
- }
- }
□ 実行結果
$ java ThreadName01 Thread Name = main
Threadクラスを継承 | Runnableインタフェースの実装 | |
---|---|---|
スーパークラス | Threadクラス | 任意 |
定義 |
class MyThread extends Thread { public void run() { //スレッドの処理 } } |
class MyRunnable implements Runnable { public void run() { //スレッドの処理 } } |
Threadオブジェクトの生成と開始 |
startメソッドを呼ぶ。 MyThread t = new MyThread(); t.start(); |
Thread経由でstartメソッドを呼ぶ。 MyRunnable r = new MyRunnable(); Thread t = new Thread(r); t.start(); |
(参考) 匿名インナークラスを使用 |
new Thread(){ public void run() { //スレッドの処理 } }.start(); |
new Thread(new Runnable() { public void run() { //スレッドの処理 } }).start(); |
- public class ThreadSub01 extends Thread {
- public void run() {
- System.out.println(getName() + " : " + "run");
- }
- }
- public class ThreadMain011 {
- public static void main(String[] args) {
- System.out.println("program-start");
- ThreadSub01 th = new ThreadSub01();
- th.start();
- ThreadSub01 th1 = new ThreadSub01();
- th1.start();
- System.out.println("program-end");
- }
- }
□ 実行結果
$ java ThreadMain011 program-start program-end Thread-1 : run Thread-2 : run
- public class ThreadMain012 {
- public static void main(String[] args) {
- System.out.println("program-start");
- ThreadSub01 th = new ThreadSub01();
- th.run();
- ThreadSub01 th1 = new ThreadSub01();
- th1.run();
- System.out.println("program-end");
- }
- }
□ 実行結果
$ java ThreadMain012 program-start Thread-0 : run Thread-1 : run program-end
- public class ThreadSub021 implements Runnable {
- public void run() {
- Thread th = Thread.currentThread();
- System.out.println(th.getName() + " run");
- }
- }
- public class ThreadMain021 {
- public static void main(String[] args) {
- System.out.println("program-start");
- ThreadSub021 thable = new ThreadSub021();
- Thread th = new Thread(thable);
- th.start();
- Thread th1 = new Thread(thable);
- th1.start();
- System.out.println( "program-end" );
- }
- }
□ 実行結果
$ java ThreadMain021 program-start Thread-1 run program-end Thread-2 run
- public class ThreadSub022 implements Runnable {
- public void run() {
- Thread th = Thread.currentThread();
- for (int i = 0; i < 10; i++) {
- System.out.println(th.getName() + " run " + i);
- }
- }
- }
- public class ThreadMain022 {
- public static void main(String[] args) {
- System.out.println("program-start");
- ThreadSub022 thable = new ThreadSub022();
- Thread th = new Thread(thable);
- th.start();
- Thread th1 = new Thread(thable);
- th1.start();
- System.out.println( "program-end" );
- }
- }
$ java ThreadMain022 program-start Thread-1 run 0 Thread-1 run 1 Thread-1 run 2 Thread-1 run 3 Thread-1 run 4 Thread-1 run 5 Thread-1 run 6 Thread-1 run 7 Thread-2 run 0 program-end Thread-2 run 1 Thread-2 run 2 Thread-2 run 3 Thread-2 run 4 Thread-2 run 5 Thread-1 run 8 Thread-1 run 9 Thread-2 run 6 Thread-2 run 7 Thread-2 run 8 Thread-2 run 9
$ java ThreadMain022 program-start Thread-1 run 0 Thread-1 run 1 Thread-1 run 2 Thread-1 run 3 Thread-1 run 4 Thread-1 run 5 Thread-1 run 6 Thread-1 run 7 Thread-1 run 8 Thread-1 run 9 program-end Thread-2 run 0 Thread-2 run 1 Thread-2 run 2 Thread-2 run 3 Thread-2 run 4 Thread-2 run 5 Thread-2 run 6 Thread-2 run 7 Thread-2 run 8 Thread-2 run 9
Linux | プリエンティブ方式 | 優先度を重視 |
---|---|---|
Windows | タイムスライス方式 | 時間で区切る |
- public class ThreadSub11 extends Thread {
- public void run() {
- for (int i = 0; i < 5; i++) {
- try {
- Thread.sleep((long)(Math.random()*1000)) ;
- } catch (InterruptedException e) {
- }
- System.out.println(getName() + " : " + "run (" + i + ")");
- }
- }
- }
- public class ThreadMain11 {
- public static void main(String[] args) {
- System.out.println("program-start");
- ThreadSub11 th = new ThreadSub11();
- th.start();
- ThreadSub11 th1 = new ThreadSub11();
- th1.start();
- System.out.println("program-end");
- }
- }
□ 実行結果
$ java ThreadMain11 program-start program-end Thread-2 : run (0) Thread-2 : run (1) Thread-2 : run (2) Thread-1 : run (0) Thread-2 : run (3) Thread-1 : run (1) Thread-1 : run (2) Thread-2 : run (4) Thread-1 : run (3) Thread-1 : run (4)
- public class ThreadMain12 {
- public static void main(String[] args) {
- System.out.println("program-start");
- ThreadSub11 th = new ThreadSub11();
- th.start();
- ThreadSub11 th1 = new ThreadSub11();
- th1.start();
- try {
- th.join();
- th1.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("program-end");
- }
- }
□ 実行結果
$ java ThreadMain12 program-start Thread-1 : run (0) Thread-1 : run (1) Thread-2 : run (0) Thread-1 : run (2) Thread-1 : run (3) Thread-2 : run (1) Thread-1 : run (4) Thread-2 : run (2) Thread-2 : run (3) Thread-2 : run (4) program-end
- // 割り込みされるスレッド
- public class Interrupt02 extends Thread {
- public void run() {
- System.out.println(getName() + " がスタートしました");
- // カレント・スレッドならば繰り返し
- while (Interrupt01.i2 == Thread.currentThread()) {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // 割り込まれたときの処理
- System.err.println("割り込みをキャッチしました");
- }
- System.out.print(".");
- }
- }
- }
- // Interrupt02 に割り込みをかけるスレッドを実装
- public class Interrupt01 extends Thread {
- static Thread i2;
- static Interrupt01 i1;
- public static void main(String args[]) {
- System.out.println("アプリケーションの停止は、CTRL+C を押下してください。");
- // スレッドの作成および開始
- i1 = new Interrupt01();
- i2 = new Thread(new Interrupt02());
- i1.start();
- i2.start();
- }
- public void run() {
- while (true) {
- try {
- Thread.sleep( ((int)(Math.random() * 10)) * 1000);
- // スレッドの実行に割り込み
- i2.interrupt();
- } catch (InterruptedException e) { }
- }
- }
- }
□ 実行結果
$ java Interrupt01 アプリケーションの停止は、CTRL+C を押下してください。 Thread-0 がスタートしました ..割り込みをキャッチしました .......割り込みをキャッチしました ......割り込みをキャッチしました .....割り込みをキャッチしました ..割り込みをキャッチしました ..割り込みをキャッチしました .......割り込みをキャッチしました
static int MAX_PRIORITY | スレッドに設定できる最高優先順位です。 | 10 |
static int MIN_PRIORITY | スレッドに設定できる最低優先順位です。 | 1 |
static int NORM_PRIORITY | スレッドに割り当てられるデフォルトの優先順位です。 | 5 |
int getPriority() | このスレッドの優先順位を返します。 |
void setPriority(int newPriority) | このスレッドの優先順位を変更します。 |
- public class Priority01 extends Thread {
- public static void main(String[] args) {
- System.out.println("Start main");
- Priority01 t1 = new Priority01();
- t1.start();
- Priority01 t2 = new Priority01();
- t2.setPriority(MAX_PRIORITY);
- t2.start();
- System.out.println("End main");
- }
- public void run() {
- System.out.println("Start " + getName());
- System.out.println("Priority = " + getPriority());
- new Priority02().start();
- System.out.println("End " + getName());
- }
- }
- public class Priority02 extends Thread {
- public void run() {
- System.out.println(" Start " + getName());
- System.out.println(" Priority = " + getPriority());
- System.out.println(" End " + getName());
- }
- }
□ 実行結果
$ java Priority01 Start main Start Thread-2 Priority = 10 End Thread-2 Start Thread-3 Priority = 10 End Thread-3 End main Start Thread-1 Priority = 5 End Thread-1 Start Thread-4 Priority = 5 End Thread-4
- // 1701
- // package server;
- // import product.*;
- import java.util.*;
- import java.net.*;
- import java.io.*;
- // 商品サーバーです。
- public class ProductServer {
- public static void main(String[] args) throws Exception {
- final int SERVER_PORT = 54321;
- TreeMap p = new TreeMap();
- SetProduct s = new SetProduct("SA01", "パソコン・セット", 10, p);
- System.out.println("セット商品のインスタンスを生成しました。 s = " + s);
- System.out.println();
- AdminProduct ap = new AdminProduct();
- ap.read(s, args[0]);
- System.out.println("セット商品のデータを設定しました。 s = " + s);
- // サーバ用ソケットの作成
- ServerSocket serversock = new ServerSocket(SERVER_PORT);
- // 非同期制御データ・オブジェクトの作成
- while (true) {
- // クライアントからの接続要求待ち
- Socket sock = serversock.accept();
- new ProductServerThread(sock, s).start();
- }
- }
- }
- //クライアントと対応するサーバーのスレッドです。
- public class ProductServerThread extends Thread {
- private Socket sock;
- private SetProduct s;
- ProductServerThread(Socket sock, SetProduct s) {
- this.sock = sock;
- this.s = s;
- }
- public void run() {
- System.out.println("socket = " + sock);
- DataInputStream dis = null;
- DataOutputStream dos = null;
- try {
- // クライアントと対話処理するストリーム、ソケットを生成
- dis = new DataInputStream(sock.getInputStream());
- dos = new DataOutputStream(sock.getOutputStream());
- // 商品コードを受け取って、対応する商品を返す
- String code = dis.readUTF();
- String result = s.query(code);
- System.out.println(" [" + code + " = " + result + "]");
- dos.writeUTF(result);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- // ストリーム、ソケットをクローズ
- dos.close();
- dis.close();
- sock.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
$ java
$ java
□ "NoSyncServer.java"
- import java.net.*;
- import java.io.*;
- // サーバにアクセスする TCP クライアント
- public class SyncTestClient {
- public static void main(String args[]) {
- final int SERVER_PORT = 54321; // サーバのポート番号
- String serverName = "localhost";
- if (args.length == 1) {
- serverName = args[0];
- }
- try {
- // ソケットの作成
- Socket sock = new Socket(serverName, SERVER_PORT);
- // サーバとの通信用の入出力ストリームの獲得
- DataOutputStream dos =
- new DataOutputStream(sock.getOutputStream());
- DataInputStream dis =
- new DataInputStream(sock.getInputStream());
- // データの受信
- String data;
- data = dis.readUTF();
- System.out.println(data);
- // ストリーム、ソケットのクローズ
- dis.close();
- dos.close();
- sock.close();
- } catch (UnknownHostException e) {
- System.err.println("Host '" + serverName + "' is unknown");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
□ "NoSyncData.java"
- import java.net.*;
- import java.io.*;
- // 複数クライアントの同時アクセスを受け付ける TCP サーバ
- public class NoSyncServer {
- public static void main(String args[]) throws Exception {
- final int SERVER_PORT = 54321; // サーバのポート番号
- // サーバ用ソケットの作成
- ServerSocket serversock = new ServerSocket(SERVER_PORT);
- // 非同期制御データ・オブジェクトの作成
- NoSyncData data = new NoSyncData();
- while (true) {
- // クライアントからの接続要求待ち
- Socket sock = serversock.accept();
- // クライアントと対話処理するスレッドの起動
- new NoSyncServerThread(sock, data).start();
- }
- }
- }
- // 接続済みクライアントと通信するスレッド
- public class NoSyncServerThread extends Thread {
- private Socket sock = null;
- NoSyncData data = null;
- NoSyncServerThread(Socket client, NoSyncData data) {
- this.sock = client;
- this.data = data;
- }
- // クライアントへのサービス
- public void run() {
- try {
- DataInputStream dis =
- new DataInputStream(sock.getInputStream());
- DataOutputStream dos =
- new DataOutputStream(sock.getOutputStream());
- // データ(処理結果)の送信
- dos.writeUTF("number = " + data.incrementNumber());
- // ストリーム、ソケットをクローズ
- dos.close();
- dis.close();
- sock.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public class NoSyncData {
- private int number = 0;
- int incrementNumber() throws Exception {
- int w = number;
- Thread.sleep(1000);
- number = w + 1;
- System.out.println("number = " + number);
- return number;
- }
- }
java SyncTestClient number = 1
java SyncTestClient number = 1
java NoSyncServer number = 1 number = 1
□ "SyncData.java"
- import java.net.*;
- import java.io.*;
- // 複数クライアントの同時アクセスを受け付ける TCP サーバ
- public class SyncServer {
- public static void main(String args[]) throws Exception {
- final int SERVER_PORT = 54321; // サーバのポート番号
- // サーバ用ソケットの作成
- ServerSocket serversock = new ServerSocket(SERVER_PORT);
- // 非同期制御データ・オブジェクトの作成
- SyncData data = new SyncData();
- while (true) {
- // クライアントからの接続要求待ち
- Socket sock = serversock.accept();
- // クライアントと対話処理するスレッドの起動
- new SyncServerThread(sock, data).start();
- }
- }
- }
- // 接続済みクライアントと通信するスレッド
- public class SyncServerThread extends Thread {
- private Socket sock = null;
- SyncData data = null;
- SyncServerThread(Socket client, SyncData data) {
- this.sock = client;
- this.data = data;
- }
- // クライアントへのサービス
- public void run() {
- try {
- DataInputStream dis =
- new DataInputStream(sock.getInputStream());
- DataOutputStream dos =
- new DataOutputStream(sock.getOutputStream());
- // データ(処理結果)の送信
- dos.writeUTF("number = " + data.incrementNumber());
- // ストリーム、ソケットをクローズ
- dos.close();
- dis.close();
- sock.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public class SyncData {
- private int number = 0;
- synchronized int incrementNumber() throws Exception {
- int w = number;
- Thread.sleep(1000);
- number = w + 1;
- System.out.println("number = " + number);
- return number;
- }
- }
java SyncTestClient number = 1
java SyncTestClient number = 2
java NoSyncServer number = 1 number = 2
ファイル名 | クラス名 | 排他制御 | 同期制御 |
---|---|---|---|
Memo01.java | Memo01, NoSyncMemo, NoSyncMemoGet, NoSyncMemoPut | - | - |
Memo02.java | Memo02, ExclSyncMemo, ExclSyncMemoGet, ExclSyncMemoPut | x | - |
Memo03.java | Memo03, SyncMemo, SyncMemoGet, SyncMemoPut | x | x |
- public class Memo01 {
- public static void main(String[] args) {
- System.out.println("Start main");
- NoSyncMemo m = new NoSyncMemo();
- new NoSyncMemoPut(m, "Hello").start();
- new NoSyncMemoPut(m, "Java").start();
- new NoSyncMemoPut(m, "World").start();
- new NoSyncMemoGet(m).start();
- new NoSyncMemoGet(m).start();
- new NoSyncMemoGet(m).start();
- System.out.println("End main");
- }
- }
- public class NoSyncMemoPut extends Thread {
- NoSyncMemo m;
- String s;
- NoSyncMemoPut(NoSyncMemo m, String s) {
- this.m = m;
- this.s = s;
- }
- public void run() {
- m.putMemo(s);
- }
- }
- public class NoSyncMemoGet extends Thread {
- NoSyncMemo m;
- NoSyncMemoGet(NoSyncMemo m) {
- this.m = m;
- }
- public void run() {
- System.out.println(m.getMemo());
- }
- }
- public class NoSyncMemo {
- private String m;
- public void putMemo(String m) {
- this.m = m;
- }
- public String getMemo() {
- return m;
- }
- }
□ 実行結果
java Memo01 Start main End main World World World
- public class Memo02 {
- public static void main(String[] args) {
- System.out.println("Start main");
- ExclMemo m = new ExclMemo();
- new ExclMemoPut(m, "Hello").start();
- new ExclMemoPut(m, "Java").start();
- new ExclMemoPut(m, "World").start();
- new ExclMemoGet(m).start();
- new ExclMemoGet(m).start();
- new ExclMemoGet(m).start();
- System.out.println("End main");
- }
- }
- public class ExclMemoPut extends Thread {
- ExclMemo m;
- String s;
- ExclMemoPut(ExclMemo m, String s) {
- this.m = m;
- this.s = s;
- }
- public void run() {
- m.putMemo(s);
- }
- }
- public class ExclMemoGet extends Thread {
- ExclMemo m;
- ExclMemoGet(ExclMemo m) {
- this.m = m;
- }
- public void run() {
- System.out.println(m.getMemo());
- }
- }
- public class ExclMemo {
- private String m;
- public synchronized void putMemo(String m) {
- this.m = m;
- }
- public synchronized String getMemo() {
- return m;
- }
- }
□ 実行結果
java Memo02 Start main End main World World World
- public class Memo03 {
- public static void main(String[] args) {
- System.out.println("Start main");
- SyncMemo m = new SyncMemo();
- new SyncMemoPut(m, "Hello").start();
- new SyncMemoPut(m, "Java").start();
- new SyncMemoPut(m, "World").start();
- new SyncMemoGet(m).start();
- new SyncMemoGet(m).start();
- new SyncMemoGet(m).start();
- System.out.println("End main");
- }
- }
- public class SyncMemoPut extends Thread {
- SyncMemo m;
- String s;
- SyncMemoPut(SyncMemo m, String s) {
- this.m = m;
- this.s = s;
- }
- public void run() {
- m.putMemo(s);
- }
- }
- public class SyncMemoGet extends Thread {
- SyncMemo m;
- SyncMemoGet(SyncMemo m) {
- this.m = m;
- }
- public void run() {
- System.out.println(m.getMemo());
- }
- }
- public class SyncMemo {
- private boolean st;
- private String m;
- public synchronized void putMemo(String m) {
- while (st) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- st = true;
- this.m = m;
- notify();
- }
- public synchronized String getMemo() {
- while (!st) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- st = false;
- notify();
- return m;
- }
- }
□ 実行結果
java Memo03 Start main End main Hello Java World
- // 1702
- // package product;
- import java.util.*;
- // セット商品クラスです。
- // ひとつまたは複数の商品を集めて、割引したものをセット商品として扱います。
- // セット商品に対するフィールドやフィールドを操作するためのメソッドを
- // 提供しています。
- public class SetProduct extends AbstractProduct implements DiscountInterface {
- private int discount; // セット商品割引率
- private Map products; // セット商品リスト
- // セット商品クラスのコンストラクター。
- public SetProduct(String code, String name, int discount, Map products) {
- setCode(code);
- setName(name);
- setDiscount(discount);
- setProducts(products);
- }
- // セット商品オブジェクトを文字列化します。
- public synchronized String toString() {
- return "[" + getCode() + ", " + getName() + ", " + getDiscount() + ", "
- + getPrice() + "]";
- }
- // 商品の売値の値を取得します。
- public synchronized int getPrice() {
- int price = 0;
- Iterator itr = products.values().iterator();
- while (itr.hasNext()) {
- price += ((Product)itr.next()).getPrice();
- }
- return (int)(price * (1 - discount / 100.0));
- }
- // 商品割引率に値を設定します。
- public synchronized void setDiscount(int discount) {
- if (discount < 10 || discount > 100) {
- this.discount = 0;
- return;
- }
- this.discount = discount;
- }
- // 商品割引率に値を設定します。
- public synchronized void setDiscount(String discount) {
- try {
- setDiscount(Integer.parseInt(discount));
- } catch (NumberFormatException e) {
- setDiscount(0);
- e.printStackTrace();
- } catch (Exception e) {
- setDiscount(0);
- e.printStackTrace();
- }
- }
- // 商品割引率の値を取得します。
- public synchronized int getDiscount() {
- return discount;
- }
- // セット商品に値を設定します。
- public synchronized void setProducts(Map products) {
- this.products = products;
- }
- // セット商品を取得します。
- public synchronized Map getProducts() {
- return products;
- }
- // 商品を追加します。
- public synchronized void add(Product product) {
- products.put(product.getCode(), product);
- }
- // 商品を更新します。
- public synchronized void update(Product product) {
- products.put(product.getCode(), product);
- }
- // 商品を削除します。
- public synchronized void remove(String code) {
- products.remove(code);
- }
- // 商品を照会します。
- public synchronized String query(String code) {
- if (!products.containsKey(code)) {
- return "[Not Found]";
- }
- return ((Product)(products.get(code))).toString();
- }
- }
$ java
$ java