java创建线程

1,继承自Thread类

public class Thread1 extends Thread{
	@Override
	public void run() {
		System.out.println(this.getName());
	}

	public static void main(String[] args) {
		Thread1 t = new Thread1();
		t.start();
	}
}

 

2,实现Runnable接口(使用Runnable接口更加灵活

public class T {
	private String name;
	
	public T(String name){
		this.name = name;
	}
	
	public String getName(){
		return this.name;
	}
}
public class Thread2 extends T implements Runnable {
	public Thread2(String name){
		super(name);
	}
	
	public void run() {
		System.out.println(this.getName());	
        }

	public static void main(String[] args) {
		Thread1 t = new Thread1("thread1");
		t.start();
	}
}

Thread类本身也是Runnable接口的一个具体实现:

public class Thread implements Runnable { ....
}

在启动线程时,一定不要使用Thread.run(),这将变成方法调用而不是启动线程,虽然Thread.start()本质上还是调用线程的run()方法

    /**
     * Causes this thread to begin execution; the Java Virtual Machine 
     * calls the <code>run</code> method of this thread. 
     * <p>
     * The result is that two threads are running concurrently: the 
     * current thread (which returns from the call to the 
     * <code>start</code> method) and the other thread (which executes its 
     * <code>run</code> method). 
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        java.lang.Thread#run()
     * @see        java.lang.Thread#stop()
     */
    public synchronized void start() {
        if (started)
            throw new IllegalThreadStateException();
        started = true;
        group.add(this);
        start0();
    }

 

转载于:https://www.cnblogs.com/sean-zou/archive/2012/11/19/3710095.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值