首页 > java > java 多线程小试

java 多线程小试

2011年4月18日 824 views

public class ThreadTest extends Thread {

	private static Object obje = new Object();

	public void run(){
		synchronized (obje) {
			for(int i=0;i<100;i++){
				try {
					if(i%10==0&&i!=0){
						System.out.println("haha");
						obje.notify();
						obje.wait();
					}
					Thread.sleep(100);
					System.out.println(this.getName()+":"+i);
				}catch (InterruptedException e) {
						e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		Thread t1 = new ThreadTest();
		Thread t2 = new ThreadTest();
		t1.start();
		t2.start();
	}
}

部分输出结果:

Thread-0:0
Thread-0:1
Thread-0:2
Thread-0:3
Thread-0:4
Thread-0:5
Thread-0:6
Thread-0:7
Thread-0:8
Thread-0:9
haha
Thread-1:0
Thread-1:1
Thread-1:2
Thread-1:3
Thread-1:4
Thread-1:5
Thread-1:6
Thread-1:7
Thread-1:8
Thread-1:9
haha
Thread-0:10
Thread-0:11
Thread-0:12
Thread-0:13
Thread-0:14
Thread-0:15
Thread-0:16
Thread-0:17
Thread-0:18
Thread-0:19
haha
Thread-1:10
Thread-1:11
Thread-1:12
Thread-1:13
Thread-1:14
Thread-1:15
Thread-1:16
Thread-1:17
Thread-1:18
Thread-1:19
haha
Thread-0:20
Thread-0:21
Thread-0:22
Thread-0:23
Thread-0:24
Thread-0:25
Thread-0:26
Thread-0:27
Thread-0:28
Thread-0:29
haha
Thread-1:20
Thread-1:21
Thread-1:22
Thread-1:23
Thread-1:24
Thread-1:25
Thread-1:26
Thread-1:27
Thread-1:28
Thread-1:29
haha

分类: java 标签: ,
  1. 本文目前尚无任何评论.