创建多线程对象,在子线程中输出1-100之间的偶数,主线程输出1-100之间的奇数

public class Test_Thread {
	public static void main(String[] args) {
		
		//3.实例化对象
		Runnable r = new MyRunnable();
		
		//4.创建Thread对象
		Thread th1 = new Thread(r);
		th1.setName("主线程");//修改线程名字
		
		//5.采用匿名内部类方式 获取Runnable实现类对象
		Runnable r2 = new Runnable() {
			public void run() {
				String name = Thread.currentThread().getName();//输出当前线程名字
				for (int i = 1; i <= 100; i++) {
					if (i % 2 ==0) {
						System.out.println(" in thread " + name + i);
					}
				}
			}
		};
		
		//创建Thread对象
		Thread th2 = new Thread(r2);
		th2.setName("次线程");
		
		//5.启动线程
		th1.start();
		th2.start();
	}

}

//1.创建Runnable实现类
class MyRunnable implements Runnable{
	//2.重写run方法
	public void run() {
		String name = Thread.currentThread().getName();
		for (int i = 1; i <= 100; i++) {
			if (i % 2 ==1) {
				System.out.println(" in main " + name + i);
			}
		}
	}
}

创建多线程对象,在子线程中输出1-100之间的偶数,主线程输出1-100之间的奇数_第1张图片

 

你可能感兴趣的:(java代码,java,jvm,开发语言)