Java多线程

Java多线程的线程类需继承于Thread类,并且需要重写run函数。

sleep休眠时使用Thread.sleep( 200 )这种形式,并且要放在try-catch语句块中。

 下面给出简单demo:

class MyThread extends Thread{
    public void run(){
        for( int i=0; i<10; ++i ){
            System.out.println( "Thread name is: " + this.getName() );
            try{
                Thread.sleep(300);    
            }
            catch( InterruptedException e ){
                System.out.println( e.getMessage() );
            }
        }
    }
}
public class TestMultiThread{ public static void main(String[] args){ MyThread thread1 = new MyThread( "ThreadA" ); MyThread thread2 = new MyThread( "ThreadB" ); //MyThread thread3 = new MyThread( "ThreadC" ); thread1.start(); thread2.start(); //thread3.start(); } }

 

posted @ 2014-04-03 11:46  丛林小阁楼  阅读(139)  评论(0编辑  收藏  举报