1. 程式人生 > >執行緒、內部類、檔案輸出

執行緒、內部類、檔案輸出

 分別用繼承Thread和實現Runnable兩種方式定義執行緒,兩種內部類,呼叫時外部類的物件訪問。

以下demo測試了三個執行緒,列印內容用檔案作為控制檯展示。

定義執行緒的兩種方式

  1. 繼承thread類
  • 繼承thread類
  • 重寫run方法
  • 呼叫start方法啟動執行緒
  1. 實現runnable介面
  • 定義類實現runnable介面
  • new Thread(runnable實現類)
  • 呼叫start方法啟動執行緒

執行緒的關閉: 通過標記flag關閉執行緒

/**
 * @author cuijiao
 *
 */
public class MutiThread {

    /**
     * @param args
     */
    public static void main(String[] args) {

        // 1.Thread
        MutiThread mt = new MutiThread();
        Thread myThread = mt.new MyTread("thread1");// 只能通過外部類的物件訪問非靜態內部類
        myThread.start();

        // 2.Runnable
        Runnable myRun = mt.new MyRunnable();
        Thread thread = new Thread(myRun, "run2");
        thread.start();

        // 3.主執行緒
        int i = 0;
        boolean flag = true;
        while (flag) {
            FileConsole.print(Thread.currentThread().getName() + i);
            i++;
            if (i >= 50) {// 通過標記flag關閉執行緒
                flag = false;
            }
        }

    }

    // 1.繼承Thread
    private class MyTread extends Thread {

        public MyTread(String name) {
            super(name);
        }

        @Override
        public void run() {
            int i = 0;
            while (true) {
                FileConsole.print(Thread.currentThread().getName() + i);
                i++;
            }
        }

    }

    // 2.實現Runnable介面
    private class MyRunnable implements Runnable {

        @Override
        public void run() {
            int i = 0;
            while (true) {
                FileConsole.print(Thread.currentThread().getName() + i);
                i++;
            }
        }

    }
}

其中列印程式碼為:


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author cuijiao
 *
 */
public class FileConsole {
    /**
     * 用檔案充當控制檯(可檢視行數無限制)
     *
     * @param str
     */
    public static void print(String str) {
        File file = new File("E:\\console.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(file, true);// 可追加內容
            bw = new BufferedWriter(fw);
            bw.write(str);
            bw.newLine();// 換行
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                    bw = null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}