码迷,mamicode.com
首页 > 编程语言 > 详细

多线程常见的3中实现方式

时间:2015-10-10 12:14:31      阅读:578      评论:0      收藏:0      [点我收藏+]

标签:

1.继承Thread类

源代码:

package com.zy.test.www.multiThread;
/**
 * 多线程实现方式1:继承Thread类
 * @author zy
 */
public class ByExtendsThread extends Thread{    
    
    public ByExtendsThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println(getName() + " 线程运行开始!");
        for (int i = 1; i <= 5; i++) {
            System.out.println(getName() + " " + i);
            try {
                sleep((int) Math.random() * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(getName() + " 线程运行结束!");
    }
    
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
        new ByExtendsThread("A").start();
        new ByExtendsThread("B").start();
        System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
    }

}

 运行效果:

main 线程运行开始!
A 线程运行开始!
main 线程运行结束!
A 1
B 线程运行开始!
B 1
A 2
B 2
A 3
B 3
A 4
B 4
A 5
B 5
A 线程运行结束!
B 线程运行结束!

 2.实现Runnable接口

源代码:

package com.zy.test.www.multiThread;

/**
 * 多线程实现方式2:实现Runnable接口
 * @author zy
 */
public class ByImplementsRunnable implements Runnable{    

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
        for (int i = 1; i <= 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            try {
                Thread.sleep((int) Math.random() * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
    }
    
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
        ByImplementsRunnable byImplementsRunnable = new ByImplementsRunnable();
        new Thread(byImplementsRunnable, "A").start();
        new Thread(byImplementsRunnable, "B").start();
        System.out.println(Thread.currentThread().getName() + " 线程运行结束!"); 
} }

  运行效果:

main 线程运行开始!
A 线程运行开始!
main 线程运行结束!
A 1
B 线程运行开始!
B 1
A 2
B 2
A 3
B 3
A 4
B 4
A 5
B 5
A 线程运行结束!
B 线程运行结束!

 

多线程常见的3中实现方式

标签:

原文地址:http://www.cnblogs.com/sunny08/p/4866137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!