Java 基于Runnable接口的线程实例

1. 功能

通过实现Runnable接口,开发线程,然后读取文件大小。

2. 代码

读取文件大小:

package org.maoge.thread;

import java.io.File;

/**
 * 读取文件大小
 */
public class ReadFileRunnable implements Runnable {

	private String fileName;

	public ReadFileRunnable(String fileName) {
		this.fileName = fileName;
	}

	@Override
	public void run() {
		File f = new File(fileName);
		if (f.exists() && f.isFile()) {
			System.out.println("[" + fileName + "] length:" + f.length());
		} else {
			System.out.println("[" + fileName + "] not exists");
		}
	}
}

3. 测试

编写测试类:

package org.maoge.thread;

/**
 * 读文件测试
 */
public class ReadFileTest {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			ReadFileRunnable writeFile = new ReadFileRunnable("D:\\temp\\" + (i + 500) + ".txt");
			Thread thread = new Thread(writeFile);
			thread.start();
		}
	}
}

4. 结果

因为我们之前通过Java 继承Thread实现线程写了10个文件,所以此处直接输出结果:

[D:\temp\500.txt] length:1000000
[D:\temp\501.txt] length:1000000
[D:\temp\504.txt] length:1000000
[D:\temp\508.txt] length:1000000
[D:\temp\503.txt] length:1000000
[D:\temp\505.txt] length:1000000
[D:\temp\506.txt] length:1000000
[D:\temp\509.txt] length:1000000
[D:\temp\502.txt] length:1000000
[D:\temp\507.txt] length:1000000
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 点我我会动 设计师:上身试试 返回首页