java线程初步认识

这里写了一个小例子,学习一下线程实现的两种方式(继承自Thread类,实现Runnable接口),以及start(开启事务,调用run方法),yield(暂停当前正在执行的线程对象,并执行其他线程。),join(等待该线程终止),sleep(指定的毫秒数内让当前正在执行的线程休眠),setPriority(设置优先级)。

 

package com.test;   
import java.util.Date;   
/**  
 * @author wangking E-mail:[email protected]  
 * @version 创建时间:2009-9-11 上午01:39:37  
 * 开了三个线程。一个timeThread,一个thread2,一个main thread。其中只有等timeThread执行完了,才能执行main thread  
 */  
public class ThreadTest {   
    public static void main(String[] args) {   
           
           
        TimeRunnable timeRunnable = new TimeRunnable("time thread");   
        Thread timeThread = new Thread(timeRunnable);   
           
        Thread2 thread2 = new Thread2("wangking");   
        thread2.setPriority(Thread.NORM_PRIORITY+2);   
        timeThread.start();   
        thread2.start();   
           
        try {   
            timeThread.join();   
        } catch (InterruptedException e) {   
            e.printStackTrace();   
        }   
           
        for(int i=0;i<100;i++){   
            System.out.println("-------main is running-----"+i);   
        }   
           
           
    }   
       
}   
//线程一   
class Thread2 extends Thread{   
       
    boolean flag = true;   
       
    public Thread2(String name){   
        super(name);   
    }   
       
    @Override  
    public void run() {   
           
        for(int i = 0;i < 100;i++){   
            System.out.println(getName()+" thread is running:" + i);   
            if(i%10 == 0){   
                try {   
                    this.sleep(1000);   
                } catch (InterruptedException e) {   
                    e.printStackTrace();   
                    return;   
                }   
                this.yield();   
            }   
        }   
           
    }   
       
    //线程二   
    public void setFlag(boolean flag){   
        this.flag = flag;   
    }   
       
}   
class TimeRunnable implements Runnable{   
       
    private String name;    //线程名称   
       
    public TimeRunnable(String name){   
        this.name = name;   
    }   
       
    public void run() {   
           
        int i = 0;   
        while(i<=10){   
               
            System.out.println("----"+this.name+" at "+new Date());   
               
            try {   
                Thread.sleep(1000);   
            } catch (InterruptedException e) {   
                return;   
            }   
            i++;   
               
        }      
           
           
           
    }   
       
} 

 

 

 

你可能感兴趣的:(java,thread,Gmail)