码迷,mamicode.com
首页 > 编程语言 > 详细

多线程基础

时间:2014-08-05 18:16:39      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:style   color   java   strong   for   art   ar   new   

java中启动多线程有两种方法,一是继承Thread类,二是实现Runnable接口。

继承Thread类:

java中正确地启动多线程不能直接调用run()方法,而是调用从Thread类中继承而来的start()方法。

class myThead01 extends Thread {
    private String name;

    public myThead01(String n) {
        this.name = n;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(name+" :"+i);
        }
    }
}

public class ThreadDemo01 {
    public static void main(String[] args) {
        myThead01 mt1 = new myThead01("A");
        myThead01 mt2 = new myThead01("B");
        mt1.start();
        mt2.start();
    }

}

实现Runnable接口:

在Thread类中提供了public Thread(Runnable target)和public Thread(Runnable target,String name)两个构造方法,

这两个构造方法都可以接受Runnable的子类实例对象,所以可以依靠此点启动多线程:

class MyThread02 implements Runnable {
    private String name;

    public MyThread02(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name + "runing,i= " + i);
        }

    }

}

public class RunnableDemo01 {
    public static void main(String[] args) {
        MyThread02 my1 = new MyThread02("AAAA");
        MyThread02 my2 = new MyThread02("BBBB");
        Thread t1 = new Thread(my1);
        Thread t2 = new Thread(my2);
        t1.start();
        t2.start();
    }
}

 

优缺点比较:

继承Thread不能保证资源共享:

class myThread04 extends Thread{
    private String nameString;
    private int tiket=5;
    public myThread04(String name){
        nameString=name;
    }
    public void run() {
        for(int i=1;i<100;i++){
            if(tiket>0){
            System.out.println(nameString+":"+tiket--);
            }
        }
    }
}
public class ThreadDemo04 {
    public static void main(String[] args) {
         myThread04 mThread01=new myThread04("aaaaaa");
         myThread04 mThread02=new myThread04("bbbbbb");
         myThread04 mThread03=new myThread04("cccccc");
        
         mThread01.start();   
         mThread02.start();
         mThread03.start();
    }
}

实现runnable可以:

class myThread05 implements Runnable {

    private int tiket = 5;
    private String nameString;

    public myThread05(String name) {
        nameString = name;
    }

    public void run() {
        for (int i = 0; i < 100; i++) {
            if (tiket > 0) {
                System.out.println(nameString + ":" + tiket--);
            }
        }
    }

}

public class RunnableDemo05 {
    public static void main(String[] args) {
        myThread05 m = new myThread05("aa");

        Thread thread = new Thread(m);
        thread.start();
    }

}

多线程基础,布布扣,bubuko.com

多线程基础

标签:style   color   java   strong   for   art   ar   new   

原文地址:http://www.cnblogs.com/vonk/p/3892396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!