java多线程的创建

线程:代码一条条的执行,分出另外一条线执行线路,多条线路同时并行执行。

创建线程的两种常见方法:

1、new Thread子类

2、new Runnable dui

public static void main(String[] args) {
	
		Thread thread = new Thread(){ //创建线程的方式1.new Thread 子类
			@Override
			public void run() {
				while(true){  //线程不停的运行
					try {
						Thread.sleep(1000);  //使当前线程休眠1秒
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("1:" + Thread.currentThread().getName());
					System.out.println("1.1:" + this.getName());
				}
			}
		};
		thread.start();
		
		//创建线程的方法2 new Runnable对象
		Thread thread2 = new Thread(new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("2:" + Thread.currentThread().getName());

				}				
				
			}
		});

		thread2.start();

运行结果:



注意:线程启动之后,会先去找自己的run()方法,当找不到自己的run()方法才去找其父类的run()方法

例子:

/*该方法会执行Thread子类的run方法, 原因:执行start之后会先去找自己的run方法即Thread自己的run方法(即1),如果没有则会去找父类的run方法(即2)*/	
		new Thread(
				new Runnable(){
					public void run() {//1
						while(true){
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							System.out.println("runnable :" + Thread.currentThread().getName());

						}							
					}
				}
		){
			public void run() {//2
				while(true){
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread :" + Thread.currentThread().getName());

				}	
			}
		}.start();
		
		
	}
执行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值