java学习笔记-Thread

java定义了创建线程的两种方法
1.实现Runnable接口
2.扩展Thread类本身

1.实现Runnable接口:

可以依托任何Runnable接口的对象来创建线程。但是为了实现Runnable接口,类需要实现run()方法。

创建了实现Runnable接口的类之后,可以在类中实例化Thread类型的对象。Thread类定义了几个构造函数,下面实例中使用的构造函数如下:

Thread(Runnable threadOb,String threadName) //该构造函数中,threadOb是实现了Runnable接口的类的实例或对象;

实例:

实现Runnable接口的类NewThread代码:

public class NewThread implements Runnable{
	Thread t;
	public NewThread() {
		//this是实现Runnable接口的类的实例
		t=new Thread(this,"Demo Thread");
		System.out.println("Child thread:"+t);
		t.start();
	}
	
	public void run() {
		try {
			for(int i=5;i>0;i--)
				System.out.println("Child thread:"+i+":"+Thread.currentThread());
			Thread.sleep(500);
		} catch (InterruptedException e) {
			System.out.println("Child Interrupted.");
		}
		System.out.println("Exiting Child thread.");
	}	
}
测试类ThreadDemo代码:

public class ThreadDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new NewThread();
		try{
			for(int i=5;i>0;i--){
				System.out.println("Main Thread:"+i+":"+Thread.currentThread());
				Thread.sleep(1000);
			}
		}catch (InterruptedException e) {
			System.out.println("Main thread Interrupted.");
		}
		System.out.println("Exiting Main thread.");
	}	
}
运行结果如下图:

ps:Thread.currentThread()方法输出的是当前线程线程名称,优先级5,线程所处的线程组main。

2.扩展Thread类:

 建一个扩展了thread的类,然后创建该类的实例。

ps:1.扩展类必须重写run方法,run新线程的入口点。

         2.扩展类的实例还必须调用start方法来开启新线程的执行。

实例:

扩展thread的类代码:

public class NewThread extends Thread {
	NewThread() {
		super("Demo Thread");
		System.out.println("Child thread:" + this);
		start();
	}

	public void run() {
		try {
			for (int i = 5; i > 0; i--)
				System.out.println("Child thread:" + i + ":"
						+ Thread.currentThread());
			Thread.sleep(500);
		} catch (InterruptedException e) {
			System.out.println("Child Interrupted.");
		}
		System.out.println("Exiting Child thread.");
	}
}
测试类DemoThread代码:

public class ThreadDemo {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new NewThread();
		try{
			for(int i=5;i>0;i--){
				System.out.println("Main Thread:"+i+":"+Thread.currentThread());
				Thread.sleep(1000);
			}
		}catch (InterruptedException e) {
			System.out.println("Main thread Interrupted.");
		}
		System.out.println("Exiting Main thread.");
	}	
}
运行结果如下图:

ps:注意在NewThread类中对super()方法的调用,这会调用以下形式的Thread构造函数:public Thread(String threadName);threadName指定了线程的名称。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值