sample16_3.java

来自「Java SE 6.0前12-16章示的示例代码,简单易学」· Java 代码 · 共 69 行

JAVA
69
字号
package wyf.jc;
//定义实现Runnable接口的类
class MyRunnable1 implements Runnable
{
	//重写run方法,指定该线程执行的代码
	public void run()
	{
		for(int i=0;i<5;i++)
		{
			System.out.println("["+i+"] 我是线程1!!!");
			//使此线程进入睡眠状态
			try
			{
				Thread.sleep(100);
			}
			catch(InterruptedException ie)
			{
				ie.printStackTrace();
			}			
		}
	}
}
//定义另外一个实现Runnable接口的类
class MyRunnable2 implements Runnable
{
	//重写run方法,指定该线程执行的代码
	public void run()
	{
		for(int i=0;i<5;i++)
		{
			System.out.println("<"+i+"> 我是线程2!!!");
			//使此线程进入睡眠状态
			try
			{
				Thread.sleep(100);
			}
			catch(InterruptedException ie)
			{
				ie.printStackTrace();
			}			
		}
	}
}
public class Sample16_3
{
	public static void main(String[] args)
	{
		//创建实现Runnable接口的类
		MyRunnable1 mr1=new MyRunnable1();
		MyRunnable2 mr2=new MyRunnable2();
		//创建线程Thread对象,并指定各自的target
		Thread t1=new Thread(mr1);
		Thread t2=new Thread(mr2);
		//启动线程t1
		t1.start();
		//使主线程进入睡眠状态
		try
		{
			Thread.sleep(5);
		}
		catch(InterruptedException ie)
		{
			ie.printStackTrace();
		}		
		//启动线程t2
		t2.start();
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?