publicclassDemo{publicstaticvoidmain(String[] args){//在说Thread类之前,先讲一下Thread类的继承
MyThread mt =newMyThread();
mt.start();for(int i =0; i <5; i++){
System.out.println("床前明月光,疑是地上霜"+ i);}}}classMyThreadextendsThread{
@Override
publicvoidrun(){for(int i =0; i <5; i++){
System.out.println("锄禾日当午,汗滴禾下土"+ i);}}}
Runnable接口和Thread类的一些方法
publicclassDemo1{publicstaticvoidmain(String[] args){
MyRunnable mr =newMyRunnable();
Thread t =newThread(mr);//调用
t.start();for(int i =0; i <5; i++){
System.out.println(Thread.currentThread().getName()+ i);//这里用到了两个方法前一个是返回当前的线程对象,后一个是返回当前的对象的名字//有名字就返回名字,没有的话,直接返回默认名字://main线程或者是Thread线程
System.out.println("床前明月光,疑是地上霜"+ i);}
t.interrupt();//这个方法是Thread方法自带的,它向catch块传递一个中断信号,由catch来判断是否中断//这个中断线程的方法也是在stop被启用之后非常热门的中断线程的方法}}classMyRunnableimplementsRunnable{//Runnable 接口的实现邮储其实和继承Thread类有异曲同工之处//后者比前者就少了一步调用,而在今后的学习中我们主要使用前者/**
* 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 Thread#run()
*/
@Override
publicvoidrun(){for(int i =0; i <10; i++){
System.out.println(Thread.currentThread().getName()+ i);try{
Thread.sleep(1000);}catch(InterruptedException e){
System.out.println("接受到了中断标记,我要中断了!");return;//将程序终止}
System.out.println("床前明月光,疑是地上霜"+ i);}}}