Java创建多线程实例

最近空闲时间学习点java的基础知识

1. 对Thread类进行派生并覆盖run方法:


public class ThreadDemo extends Thread {

    ThreadDemo(){}
    ThreadDemo(String szName)
    {
        super(szName);
    }

    public void run()
    {
        for (int count = 1, row = 1;row < 10; row++, count++)
        {
            for (int i = 0; i< count; i++)
            {
                System.out.print('*');
            }
            System.out.println();
        }
    }   
    public static void main(String argv[]) {
        // TODO Auto-generated method stub
        ThreadDemo td1 = new ThreadDemo();
        ThreadDemo td2 = new ThreadDemo();
        ThreadDemo td3 = new ThreadDemo();
        td1.start();
        td2.start();
        td3.start();
    }
}

2. 通过runnable接口实现:


class ThreadDemo implements Runnable {
    public void run()
    {
        for (int count = 1,row = 1;row < 10;row++,count++)
        {
            for (int i = 0; i < count;i++)
            {
                System.out.print('*');;
            }
            System.out.println();
        }
    }
    public static void main(String argv[]){
        Runnable rb = new ThreadDemo();
        Thread td1 = new Thread(rb);
        Thread td2 = new Thread(rb);
        Thread td3 = new Thread(rb);
        td1.start();
        td2.start();
        td3.start();
    }
}

你可能感兴趣的:(Java创建多线程实例)