Java 继承Thread实现线程

1. 知识点

实现线程非常简单,通过继承Thread类即可,继承后的run()方法会在单独的线程中跑。

2. 实现

通过继承Thread实现一个线程,功能是往文件中写点东西。

package org.maoge.thread;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 写文件线程
 */
public class WriteFileThread extends Thread {
	private String fileName;

	public WriteFileThread(String filename) {
		this.fileName = filename;
	}

	@Override
	public void run() {
		byte buffer[] = new byte[1000000];
		OutputStream out = null;
		try {
			out = new FileOutputStream(fileName);
			out.write(buffer, 0, buffer.length);
			System.out.println("[" + fileName + "]-endTime:" + System.currentTimeMillis());
		} catch (Exception ex) {
			System.out.println(ex.toString());
		} finally {
			try {
				out.close();
			} catch (IOException ioEx) {
				System.out.println(ioEx.toString());
			}
		}
	}
}

3. 测试

/**
 * 写文件测试
 */
public class WriteFileTest {
	public static void main(String[] args) {
		System.out.println("startTime:" + System.currentTimeMillis());
		for (int i = 0; i < 10; i++) {
			WriteFileThread writeFile = new WriteFileThread("D:\\temp\\" + (i + 500) + ".txt");
			writeFile.start();
		}
	}
}

运行结果如下,注意观察能发现,不是开始的早就结束的早。

startTime:1586956308113
[D:\temp\500.txt]-endTime:1586956308116
[D:\temp\501.txt]-endTime:1586956308116
[D:\temp\502.txt]-endTime:1586956308116
[D:\temp\506.txt]-endTime:1586956308117
[D:\temp\505.txt]-endTime:1586956308119
[D:\temp\504.txt]-endTime:1586956308120
[D:\temp\507.txt]-endTime:1586956308120
[D:\temp\503.txt]-endTime:1586956308120
[D:\temp\508.txt]-endTime:1586956308121
[D:\temp\509.txt]-endTime:1586956308121

如有问题请扫码联系我
在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页