认识Java多线程

来源:互联网 发布:淘宝怎么发买家秀 编辑:程序博客网 时间:2024/05/16 10:10

1.进程与线程的区别

·线程是在进程的基础上进行划分的

·线程消失了进程不会消失,而进程消失了线程一定会消失

2.Java进程实现的两种实现方式

·继承java.lang.Thread类,也是Runnable的实现

·实现java.lang.Runnable接口

3.线程的启动:通过调用start()方法完成,实际上调用的还是run()方法

 public synchronized void start() {        /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added  * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW".         */        if (threadStatus != 0 || this != me)            throw new IllegalThreadStateException();        group.add(this);        start0();        if (stopBeforeStart) {    stop0(throwableFromStop);}    }
4.在使用多线程的实现中,建议通过Runnable接口实现,这样在开发中可以避免接口单实现所带来的开发局限,同时也可以达到资源共享的目的,也增强了程序的健壮性,代码能够被多个程序共享,代码与数据是独立的,如卖票程序:

class MyThread extends Thread{// 继承Thread类,作为线程的实现类private int ticket = 5 ;// 表示一共有5张票public void run(){// 覆写run()方法,作为线程 的操作主体for(int i=0;i<100;i++){if(this.ticket>0){System.out.println("卖票:ticket = " + ticket--) ;}}}};public class ThreadDemo04{public static void main(String args[]){MyThread mt1 = new MyThread() ; // 实例化对象MyThread mt2 = new MyThread() ; // 实例化对象MyThread mt3 = new MyThread() ; // 实例化对象mt1.run() ;// 调用线程主体mt2.run() ;// 调用线程主体mt3.run() ;// 调用线程主体}};

5.多线程也是有固定状态的:

·创建状态:准备好了一个多线程对象 Thread t = new Thread()

·就绪状态:调用了start()方法,并不是立刻执行,而是要等到CPU进行调度

·运行状态:执行run()方法

·阻塞状态:暂时停止执行,可将资源交给其他线程使用

·终止状态(消亡状态):线程执行完毕了,不再使用

原创粉丝点击