`

java多线程例子

阅读更多
第一个例子
package timeprinter;

import java.util.Date;

public class TimePrinter implements Runnable {

	int pauseTime;
	String name;

	public TimePrinter(int x, String n) {
		pauseTime = x;
		name = n;
	}

	/**
	 * @param args
	 *            当使用 runnable 接口时,您不能直接创建所需类的对象并运行它;必须从 Thread 类的一个实例内部运行它
	 * 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// TimePrinter tp1 = new TimePrinter(1000, "Fast Guy"); 继承Thread
		// tp1.start();
		// TimePrinter tp2 = new TimePrinter(3000, "Slow Guy");
		// tp2.start();
		Thread t1 = new Thread(new TimePrinter(1000, "Fast Guy"));
		t1.start();
		Thread t2 = new Thread(new TimePrinter(3000, "Slow Guy"));
		t2.start();
	}

	private void start() {
		this.run();
	}

	@Override
	public void run() {
		while (true) {
			try {
				System.out.println(name + ":"
						+ new Date(System.currentTimeMillis()));
				Thread.sleep(pauseTime);
			} catch (Exception e) {
				System.out.println(e);
			}
		}

	}

}


程序一直不停的执行,结果如下:
Fast Guy:Thu Aug 19 16:13:55 GMT+08:00 2010
Slow Guy:Thu Aug 19 16:13:55 GMT+08:00 2010
Fast Guy:Thu Aug 19 16:13:56 GMT+08:00 2010
Fast Guy:Thu Aug 19 16:13:57 GMT+08:00 2010
Slow Guy:Thu Aug 19 16:13:58 GMT+08:00 2010
。。。
。。。

第二个例子


//扩展java.lang.Thread类
 
/**
 * File Name:   TestMitiThread.java
 * Created by:  IntelliJ IDEA.2010-7-12
 * Copyright:   Copyright (c) 2003-2006
 * Company:     Lavasoft( [url]http://lavasoft.blog.51cto.com/[/url])
 * Author:      leizhimin
 * Modifier:    leizhimin
 * Date Time:   2007-5-17 10:03:12
 * Readme:      通过扩展Thread类实现多线程
 */
public class TestMitiThread {
    public static void main(String[] rags) {
        System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
        new MitiSay("A").start();
        new MitiSay("B").start();
        System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
    }
}
 
class MitiSay extends Thread {
    public MitiSay(String threadName) {
        super(threadName);
    }
 
    public void run() {
        System.out.println(getName() + " 线程运行开始!");
        for (int i = 0; i < 10; i++) {
            System.out.println(i + " " + getName());
            try {
                sleep((int) Math.random() * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(getName() + " 线程运行结束!");
    }
}


main 线程运行开始!
A 线程运行开始!
0 A
main 线程运行结束!
1 A
B 线程运行开始!
0 B
2 A
1 B
3 A
2 B
4 A
3 B
5 A
4 B
6 A
5 B
7 A
6 B
8 A
7 B
9 A
8 B
A 线程运行结束!
9 B
B 线程运行结束!
分享到:
评论
1 楼 springdata 2014-08-05  
java多线程实例demo源代码下载:http://www.zuidaima.com/share/k%E7%BA%BF%E7%A8%8B-p1-s1.htm

相关推荐

Global site tag (gtag.js) - Google Analytics