java多线程的两种方法

自己在学习java,学到多线程,发个帖子。大哥们别喷,论坛有好多像我一样的在学习的,看了对初学者会有一定帮助的

方法一:继承Thread创建线程

class MyThread1 extends Thread{
	public void run()
	{
		for(int i=0;i<10;i++)
		{
			try
			{
				Thread.sleep(100);
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(i+"MyThread1");
		}
	}
}
public class MyThread
{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread1 tt=new MyThread1();
		tt.start();
		for(int i=0;i<10;i++)
		{
			try
			{
				Thread.sleep(100);
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(i+"MyThread");
		}

	}

}

方法二:实现Runnable借口

class MyThread implements Runnable

{
	public void run()
	{
		for(int i=0;i<10;i++)
		{
			try
			{
				Thread.sleep(100);
				
			 
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(i+"MyThread");
		}
		
		
	}
	
	
}

public class RunnableTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread my=new MyThread();
		Thread tt=new Thread(my);
		tt.start();
		for(int i=0;i<10;i++)
		{
			try
			{
				Thread.sleep(100);
				
			 
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(i+"RunnableTest");
		}
		
		
		

	}

}

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