Java线程简单调用


实现接口:
接口:Runnable
重写方法:run()

调用方式:obj.run();


public class MutilThreadRunable implements Runnable {

	private String threadName;
	private int count;

	public MutilThreadRunable(String threadName, int count) {
		this.threadName = threadName;
		this.count = count;
	}

	@Override
	public void run() {

		while (count < 20) {
			System.out.println(this.threadName);
			count++;
			try {

				Thread.sleep(1000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public String getThreadName() {
		return threadName;
	}

	public void setThreadName(String threadName) {
		this.threadName = threadName;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

}

	public static void main(String[] args) {

		MutilThreadRunable mtr0 = new MutilThreadRunable("王五", 15);
		MutilThreadRunable mtr1 = new MutilThreadRunable("赵六", 15);

		mtr0.run();
		mtr1.run();

	}


继承线程类
类名:Thread
重写方法:run()

调用方法:obj.start()

public class MutilThread extends Thread {

	private String threadName;
	private int count;

	public MutilThread(String threadName, int count) {
		this.threadName = threadName;
		this.count = count;
	}

	@Override
	public void run() {

		while (count < 5) {
			System.out.println(threadName);
			count++;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	public String getThreadName() {
		return threadName;
	}

	public void setThreadName(String threadName) {
		this.threadName = threadName;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
}

	public static void main(String[] args) {

		MutilThread mt0 = new MutilThread("张三", 0);
		MutilThread mt1 = new MutilThread("李四", 0);

		mt0.start();
		mt1.start();

	}

Runnable接口代码:

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used 
     * to create a thread, starting the thread causes the object's 
     * <code>run</code> method to be called in that separately executing 
     * thread. 
     * <p>
     * The general contract of the method <code>run</code> is that it may 
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Thread类实现了Runnable接口。

public class Thread implements Runnable { ...}

一般来说,用接口的比较多一些,因为Java中一个类智能继承一次,但是可以实现多个接口。
这两种方式的调用方式也不同:
Runnable接口使用run()调用;
Thread类使用start()方法调用;

这两种实现方式不管是哪种,他们都包含了wait()方法,也包含notify()和notifyAll()方法;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值