72

package com.haizhitao.thread;

public class ThreadTest4
{
	public static void main(String[] args)
	{
		Example example = new Example();
		
		TheThread t1 = new TheThread(example);
		
		example = new Example();
		
		TheThread2 t2 = new TheThread2(example);
		
		t1.start();
		t2.start();
	}
}

class Example
{
	public synchronized void execute()
	{
		for(int i = 0; i < 20; i++)
		{
			try
			{
				Thread.sleep((long)(Math.random() * 1000));
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			System.out.println("hello: " + i);
		}
	}
	
	public synchronized void execute2()
	{
		for(int i = 0; i < 20; i++)
		{
			try
			{
				Thread.sleep((long)(Math.random() * 1000));
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			System.out.println("world: " + i);
		}
	}
}

class TheThread extends Thread
{
	private Example example;
	
	public TheThread(Example example)
	{
		this.example = example;
	}
	
	@Override
	public void run()
	{
		example.execute();
	}
}

class TheThread2 extends Thread
{
	private Example example;
	
	public TheThread2(Example example)
	{
		this.example = example;
	}
	
	@Override
	public void run()
	{
		example.execute2();
	}
}

//output:
//	world: 0
//	world: 1
//	hello: 0
//	hello: 1
//	world: 2
//	hello: 2
//	hello: 3
//	world: 3
//	world: 4
//	hello: 4
//	hello: 5
//	world: 5
//	world: 6
//	world: 7
//	world: 8
//	hello: 6
//	hello: 7
//	world: 9
//	hello: 8
//	world: 10
//	hello: 9
//	world: 11
//	hello: 10
//	world: 12
//	hello: 11
//	world: 13
//	world: 14
//	hello: 12
//	world: 15
//	hello: 13
//	world: 16
//	hello: 14
//	world: 17
//	world: 18
//	hello: 15
//	world: 19
//	hello: 16
//	hello: 17
//	hello: 18
//	hello: 19

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值