天天看點

[Java基礎]-- java實作多線程的一種簡單方式

建立一個Thread類,實作Runable接口:

代碼實作如下

package test.local;

/**
 * Document:本類作用---->
 * User: yangjf
 * Date: 2016072016/7/1021:07
 */
public class TheadTest {
    public static void createString(){
        try{
            for(int i=0;i<200;i++){
                System.out.println("第"+i+"個:"+i);
                Thread.sleep(1000);
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Thread th1=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("啟動第一個線程");
                createString();
                System.out.println("結束第一個線程");

            }
        });
        Thread th2=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("啟動第2個線程");
                createString();
                System.out.println("結束第2個線程");
            }
        });
        Thread th3=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("啟動第3個線程");
                createString();
                System.out.println("結束第3個線程");
            }
        });
        th1.start();
        th2.start();
        th3.start();
    }
}