java多线程实例讲解


class Thread1 extends Thread
{
    public void run()
    {
        //在 run() 方法中放入线程要完成的工作

        //这里我们把两个线程各自的工作设置为打印 100 次信息
        for (int i = 0; i < 10; ++i)
        {
            System.out.println("Hello! This is " + i);
        }

        //在这个循环结束后,线程便会自动结束
    }
}

class Thread2 implements Runnable {
    //与 Thread1 不同,如果当一个线程已经继承了另一个类时,就建议你通过实现 Runnable 接口来构造

    public void run()
    {
        for (int i = 0; i < 10; ++i)
        {
            System.out.println("Thanks. There is " + i);
        }
    }
}

public class CreateThread {

    public static void main(String[] args)
    {
        Thread1 thread1 = new Thread1();
        //声明一个 Thread1 对象,这个 Thread1 类继承自 Thread 类的

        Thread thread2 = new Thread(new Thread2());
        //传递一个匿名对象作为参数

        thread1.start();
        thread2.start();
        //启动线程
    }
}

猜你喜欢

转载自blog.csdn.net/qq_20799821/article/details/105879493