java的线程

多任务与多线程:多任务属于系统级的各个应用之间的关系,而多线程属于应用级的一个应用的多个功能之间的关系

创建线程的两种方式:

实现Runnable接口

class sunclass {}

class SumThread extends sumclass imlements Runnable{}

public class **{public void main(){SumThread st=new SumThread();Thread t=new Thread(st,"threadname");t.start();}} 

继承Thread类(直接继承thread类,或者使用匿名嵌套类)

class SumThread extends Thread{
    private long length;
    public SumThread(long length,String name){
        super(name);
        this.length=length;
    }
    public void run(){
        long temp=0;
        for(int i=1;i<=length;i++){
            try {
                Thread.sleep((int)(Math.random()*10));
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            temp+=i;
        }
        System.out.println(Thread.currentThread()+"zonghe:"+temp);
    }
}
public class Thread1 {
    public static void main(String[] args) {
        System.out.println("线程");
        System.out.println(Thread.currentThread());
        SumThread st1=new SumThread(150,"线程1");
        st1.start();
        new Thread("线程2"){
            int length=150;
            public void run(){
                long temp=0;
                for(int i=1;i<=length;i++){
                    try {
                        Thread.sleep((int)(Math.random()*10));
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    temp+=i;
                }
                System.out.println(Thread.currentThread()+"zonghe:"+temp);
            }
        }.start();
}}

 

posted @ 2016-05-05 21:13  风雨缠舟  阅读(155)  评论(0编辑  收藏  举报