java多线程例子!

public class ThreadDemo
{
	public static void main(String [] args)
	{
		ThreadTest t=new ThreadTest();
		Thread t1=new Thread(t);
		Thread t2=new Thread(t);
		Thread t3=new Thread(t);
		Thread t4=new Thread(t);
		Thread t5=new Thread(t);
		Thread t6=new Thread(t);
		Thread t7=new Thread(t);
		Thread t8=new Thread(t);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
		t7.start();
		t8.start();
	}
}
class ThreadTest extends Thread  
{
	private int sum=0;
	String str=new String("");
	public void run()
	{
		while(true)
		{
			synchronized(str){
				if(sum<=10)
			{
					try
					{	
					Thread.sleep(10);
					}
					catch(Exception e){}
			System.out.println(Thread.currentThread().getName() +
				" now sum is: " + sum++);
			}
			}
		}
	}
}

你可能感兴趣的:(java,thread,多线程)