Java中实现多线程的两种方式

/**
 * 使用Thread类模拟4个售票窗口共同卖100张火车票的程序
 * 
 * 没有共享数据,每一个线程各卖100张火车票
 * 
 * @author jiqinlin
 * */public class ThreadTest {    public static void main(String[] args){        new MyThread().start();        new MyThread().start();        new MyThread().start();        new MyThread().start();
    }    
    public static class MyThread extends Thread{        //车票数量        private int tickets=100;
        @Override        public void run() {            while(tickets>0){
                System.out.println(this.getName()+"卖出第【"+tickets--+"】张火车票");
            }
        }
    }
}


/**
 * 使用Runnable接口模拟4个售票窗口共同卖100张火车票的程序
 * 
 * 共享数据,4个线程共同卖这100张火车票
 * @author jiqinlin
 * */public class RunnableTest {    public static void main(String[] args) {
        Runnable runnable=new MyThread();        new Thread(runnable).start();        new Thread(runnable).start();        new Thread(runnable).start();        new Thread(runnable).start();
    }    
    public static class MyThread implements Runnable{        //车票数量        private int tickets=100;        public void run() {            while(tickets>0){
                System.out.println(Thread.currentThread().getName()+"卖出第【"+tickets--+"】张火车票");
            }
        }
        
    }
}


采用继承Thread类方式: java

(1)优势:编写简单,若是须要访问当前线程,无需使用Thread.currentThread()方法,直接使用this,便可得到当前线程。 编程

(2)缺点:由于线程类已经继承了Thread类,因此不能再继承其余的父类。 采用实现Runnable接口方式:ide

采用实现Runnable接口的方式: this

(1)优势:线程类只是实现了Runable接口,还能够继承其余的类。在这种方式下,能够多个线程共享同一个目标对象,因此线程

很是适合多个相同线程来处理同一份资源的状况,从而能够将CPU代码和数据分开,造成清晰的模型,较好地体现了面向对象对象

的思想。继承

(2)缺点:编程稍微复杂,若是须要访问当前线程,必须使用Thread.currentThread()方法。接口

相关文章
相关标签/搜索