多线程

来源:互联网 发布:syslog tcp默认端口 编辑:程序博客网 时间:2024/06/07 19:35

<李兴华视频笔记-2012-02-27>

一、进程与线程

进程消失,线程肯定消失;线程消失,进程不一定消失

二、Java的多线程实现

1.Thread类

        java.lang包会在程序运行时自动导入

2.启动线程

        必须使用Thread类中的start()方法


class MyThread extends Thread
{
    private String name ;
    public MyThread(String name){
        this.name = name ;
    }
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println(name + "运行,i=" +i);
        }
    }
}
public class ThreadDemo01
{
    public static void main(String args[]){
        MyThread mt1 = new MyThread("线程A") ;
        MyThread mt2 = new MyThread("线程B") ;
        mt1.start();
        mt2.start();
    }
}

程序运行效果:

(哪个线程先抢到CPU资源,哪个线程直接执行)

3.Thread().start()方法

    public synchronized void start() {
        if (threadStatus != 0)
            throw new IllegalThreadStateException();
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
            }
        }
    }

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

class MyThread extends Thread
{
    private String name ;
    public MyThread(String name){
        this.name = name ;
    }
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println(name + "运行,i=" +i);
        }
    }
}
public class ThreadDemo01
{
    public static void main(String args[]){
        MyThread mt1 = new MyThread("线程A") ;
        MyThread mt2 = new MyThread("线程B") ;
        mt1.start();
        mt1.start();
    }
}



三.Runnable接口

Runnable中只有run()方法

Thread(Runnable target)
          分配新的 Thread 对象。

class MyThread implements Runnable
{
    private String name ;
    public MyThread(String name){
        this.name = name ;
    }
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println(name + "运行,i=" +i);
        }
    }
}
public class ThreadDemo01
{
    public static void main(String args[]){
        MyThread mt1 = new MyThread("线程A") ;
        MyThread mt2 = new MyThread("线程B") ;
        Thread t1 = new Thread(mt1) ;
        Thread t2 = new Thread(mt2) ;
        t1.start() ;
        t2.start() ;
    }
}


1.Thread类和Runnable接口

    Thread类implementRunnable

    使用Thread类操作多线程时,无法实现资源的共享;使用Runnable接口,能够实现资源的共享





原创粉丝点击