更新时间:2022-07-14 GMT+08:00
分享

多线程任务

功能简介

建立多线程任务,同时启动多个实例执行文件操作。

代码样例

如下是删除文件的代码片段,详细代码请参考com.huawei.bigdata.hdfs.examples中的HdfsExample类。

 // 业务示例2:多线程
final int THREAD_COUNT = 2;
for (int threadNum = 0; threadNum < THREAD_COUNT; threadNum++) {
    HdfsExampleThread example_thread = new HdfsExampleThread("hdfs_example_" + threadNum);
    example_thread.start();
}


class HdfsExampleThread extends Thread {
    private final static Log LOG = LogFactory.getLog(HdfsExampleThread.class.getName());
    /**
     * 
     * @param threadName
     */
    public HdfsExampleThread(String threadName) {
        super(threadName);
    }
    public void run() {
        HdfsExample example;
        try {
            example = new HdfsExample("/user/hdfs-examples/" + getName(), "test.txt");
            example.test();
        } catch (IOException e) {
            LOG.error(e);
        }
    }
}

example.test()方法即为对文件的操作,代码如下:

/**
 * HDFS 操作实例
 * 
 * @throws IOException
 * @throws ParameterException
 * 
 * @throws Exception
 *
 */
public void test() throws IOException {
    // 创建目录
    mkdir();

    // 写文件
    write();

    // 追加文件内容
    append();

    // 读文件
    read();

    // 删除文件
    delete();

    // 删除目录
    rmdir();
}

分享:

    相关文档

    相关产品