Java多线程实现(1)---Thread类和Runnable接口

多线程的编程支持是Java的一大特色
下边看一下多线程的实现

1、继承Thread类实现多线程

class Mythread extends Thread{
    private String title;
    public Mythread(String title) {
    this.title = title;
}

public void run() {
    for(int i = 0; i < 10; i++) {
        System.out.println(this.title+"i = "+i);
        }
    }
}

public class Thread1 {
    public static void main(String[] args) {
        Mythread mythread1 = new Mythread("thread1");
        Mythread mythread2 = new Mythread("thread2");
        Mythread mythread3 = new Mythread("thread3");
        mythread1.run();
        mythread2.run();
        mythread3.run();
    }
}

这个时候只是做了一个顺序打印,和多线程一点关系都没有。正确启动多线程的方式是调用Thread类中的start()方
法。
启动多线程:public synchronized void start()此方法会自动调用线程的run()方法

正确启动多线程

/*
 *继承Thread类实现多线程 
 */

class Mythread extends Thread{
    private String title;
    public Mythread(String title) {
    this.title = title;
}

public void run() {
    for(int i = 0; i < 10; i++) {
        System.out.println(this.title+"i = "+i);
        }
    }
}

public class Thread1 {
    public static void main(String[] args) {
        Mythread mythread1 = new Mythread("thread1");
        Mythread mythread2 = new Mythread("thread2");
        Mythread mythread3 = new Mythread("thread3");
        mythread1.start();
        mythread2.start();
        mythread3.start();
    }       
}

此时再次执行代码发现,所有的线程对象变味了交替执行

可以通过eclipse查看start的源码
1. 首先我们看到在start()方法中抛出IllegalThreadStateException异常,按照原有的处理方式,应当在
调用处进行异常处理,而此处没有处理也不会报错,因此是一个RunTimeException,这个异常的产生
只是因为你重复启动了线程才会产生。所以,每一个线程对象只能够启动一次
2. 下面我们看到了在start()方法中调用了start0()方法,而这个方法是一个只声明而未实现的方法同时使用
native关键字进行定义。

在这我们需要说明下:
线程的调用是从start开始由start0到JVM中准备好资源然后在回调run方法的。

2、Runnable()接口实现多线程

Thread类的核心功能是进行线程的启动。如果一个类为了实现多线程直接去继承Thread类就会有但继承局限。在
java中又提供有另外一种实现模式:Runnable接口。

/*
 * Runnable() 接口实现多线程
 */
class Mythread implements Runnable{
    private String title;
    public Mythread(String title) {
    this.title = title;
}

public void run() {
    for(int i = 0; i < 10; i++) {
        System.out.println(this.title+" = "+i);
        }
    }
}

//启动多线程
public class Thread2 {
    public static void main(String[] args) {
        Mythread mythread1 = new Mythread("A");
        Mythread mythread2 = new Mythread("B");
        Mythread mythread3 = new Mythread("C");
        new Thread(mythread1).start();
        new Thread(mythread2).start();
        new Thread(mythread3).start();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值