多线程

1.创建多线程的方式

两者都可实现多线程,一种是继承Thread类,一种是实现Runnable接口。实现方式分别如下

1)继承Thread类

public class Test {
    public static void main(String[] args)  {
        MyThread thread = new MyThread();
        thread.start();     //只有通过start才会启动子线程并调用run方法,直接调用run方法和调用普通方法一样不会启动子线程
    }
}
 
class MyThread extends Thread{
    private static int num = 0;
     
    public MyThread(){
        num++;
    }
     
    @Override
    public void run() {
        System.out.println("主动创建的第"+num+"个线程");
    }
}

2)实现Runnable接口

必须将Runnable作为Thread类的参数,再使用Thread的start方法来启动线程执行该任务

public class Test {
    public static void main(String[] args)  {
        System.out.println("主线程ID:"+Thread.currentThread().getId());
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}
 
class MyRunnable implements Runnable{
    public MyRunnable() {  
    }
     
    @Override
    public void run() {
        System.out.println("子线程ID:"+Thread.currentThread().getId());
    }
}

2.Thread和Runnable的区别和联系

Runnable相比Thread的优点有:

(1)避免单继承的局限性,继承了Thread类后就无法再继承其他类;

(2)适合多个相同代码处理统一资源的情况,代码和数据分隔开,提高程序的健壮性。一个Thread只能被start一次,但是一个Runnable可以放到

多个Thread中被start多次。

举例如下(卖票程序)

Thread的实现方式

class MyThread extends Thread{  
    private int ticket=10; 
    public void run(){  
        for(int i=0;i<20;i++){  
            if(this.ticket>0){  
                System.out.println("卖票:ticket"+this.ticket--);  
            }  
        }  
    }  
}; 
public class ThreadTicket {  
    public static void main(String[] args) {  
        MyThread mt1=new MyThread();  
        MyThread mt2=new MyThread();  
        MyThread mt3=new MyThread();  
        mt1.start();//每个线程都各卖了10张,共卖了30张票  
        mt2.start();//但实际只有10张票,每个线程都卖自己的票  
        mt3.start();//没有达到资源共享  
    }  
} 

Runnable的实现方式:

class MyThread implements Runnable{  
    private int ticket=10;  
    public void run(){  
        for(int i=0;i<20;i++){  
            if(this.ticket>0){  
                System.out.println("卖票:ticket"+this.ticket--);  
            }  
        }  
    }  
}  

public class RunnableTicket {  
    public static void main(String[] args) {  
        MyThread mt=new MyThread();  
        new Thread(mt).start();//同一个mt,但是在Thread中就不可以,如果用同一个实例化对象mt,就会出现异常  
        new Thread(mt).start();  
        new Thread(mt).start();  
    }  
}; 

由上例可见,Thread的实现方式中每个线程都卖出了10张票,实际卖出了30张票,而Runnable的实现方式中三个线程一共卖出了10张票,达到了

资源共享的目的

3.线程的状态

线程的状态有:New(创建)、Runnable(就绪)、Blocked(阻塞)、Running(运行)、Dead(消亡)

其相互之间的关系如下图


Thread类的方法与线程状态之间的对应关系如下图:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值