Runnable初级问题

问题:java Runnable的一个很菜的问题

class  test implements Runnable
{
 public void run() 
 {
  System.out.println("test");
 }
}
public class Run 
{
 public static void main(String[] args) 
 {
  test a = new test();
  a.start();
 }

}
////////////////////////////////////////
这段代码有什么问题吗?
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 The method start() is undefined for the type test 
回答:Thread是系统给你的资源,有了Thread你才有从CPU那里得到可执行时间片的权力, Thread并不认识你的程序,不知道有test 这样的类,因为编序员有千千万,每个人命名都不一样,想要做的事都不一样, 
所以 Thread只认识一个! 那就是Runnable 。 Thread认识Runnable 并且知道Runnable 里面有一个run方法. 一旦调用Thread的start方法,Runnable 方法里的run就会被Thread自动运行。 

所以,当我们把我们的类继承(这里应该叫实现接口)自Runnable 的时候,我们的程序就是属于Runnable 一个类型的了。 虽然是Runnable 的子类,但人家认识你爸爸,当然也知道了你。 
Thread可以不管你内部有什么情况,他只管你有run()方法就行了,他就调start让你去运行run 所以我们在run里面写点东西,这样就可以让系统运行我们想要做的代码了。 

是不是很通俗很易懂呢? 
所以要运行线程的步骤是, 
1。生成我们自己的类对象 
2。从系统那里得到Thread 
3。让Threa调我们的类对象,让其start起来 


代码: 
test a=new test(); 
Thread thread=new Thread(a); //Thread需要一个参数,就是你编的线程类,这样他就认识了你的线程,也有资格向系统申请拿到CPU时间片
thread.start(); 

你可以简单点写: 
new Thread(a).start(); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值