多线程

<李兴华视频笔记-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接口,能够实现资源的共享





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值