线程的简单使用

xu.wang

发布于 2018.12.21 15:42 阅读 2275 评论 0

本文章简单介绍线程的使用,以及向线程中传参的方法,由于《阿里巴巴JAVA规范》中推荐使用implement Runable的方式,所以在此只介绍此方式来编写。

package com.lindasoft.util;

import org.junit.Test;

/**
 * @author xu.wang 
 */
public class ThreadTest {


    @Test
    public void threadTest() {

        //使用构造器传值
        TestThread testThread1 = new TestThread("test thread name ");
        //使用set方法进行传值
        testThread1.setValue(" test thread value ");
        //启动线程
        Thread thread1 = new Thread(testThread1);
        thread1.start();
    }

}

class TestThread implements Runnable{

    String name;
    String value;

    public TestThread(String name){
        this.name = name;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());

        for(int i = 0;i<5;i++){
            System.out.println(name + i + value);
        }

    }
}