Java中多线程的使用

Java中多线程的使用

在这里插入图片描述

  • 第一种继承Thread类

    1.创建自定义类并继承Thread类。

    2.重写Thread类中的run方法,并编写该线程的业务逻辑代码。

    package com.mie.test;
    
    public class MyThread1 extends Thread{
    
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
            //定义业务逻辑
    		for (int i = 0; i < 1000; i++) {
    			System.out.println("++++++mythread1");
    		}
    	}
    	
    }
    
    
    package com.mie.test;
    
    public class MyThread2 extends Thread{
    
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
            //定义业务逻辑
    		for (int i = 0; i < 1000; i++) {
    			System.out.println("--------mythread2");
    		}
    	}
    	
    
    }
    
    

    3.使用

    package com.mie.test;
    
    public class Test {
    	public static void main(String[] args) {
            //开启两个子线程
    		MyThread1 myThread1=new MyThread1();
    		MyThread2 myThread2=new MyThread2();
    		myThread1.start();
    		myThread2.start();
    		}
    	
    
    }
    

    注意:不能通过run方法来调用线程的任务,因为run方法相当于普通对象的执行,并不会去抢占CPU资源。

    只有通过start方法才能开启线程,进而去抢占CPU资源,当某个线程抢占到CPU资源,会自动调用run方法。

    • 第二种实现Runnable接口

​ 1.创建自定义类并实现Runnable接口

​ 2.实现run方法,编写该线程的业务逻辑代码。

package com.mie.test;

public class MyRunnable1 implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("+++++myrunnable1");
		}		
		
	}

}

package com.mie.test;

public class MyRunnable2 implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("------myrunnable2");
		}
		
	}

}

3.使用

package com.mie.test;

public class Test {
	public static void main(String[] args) {
//		MyThread1 myThread1=new MyThread1();
//		MyThread2 myThread2=new MyThread2();
//		myThread1.start();
//		myThread2.start();
		MyRunnable1 myRunnable1=new MyRunnable1();
		Thread thread1=new Thread(myRunnable1);
		thread1.start();
		MyRunnable2 myRunnable2=new MyRunnable2();
		Thread thread2=new Thread(myRunnable2);
		thread2.start();
		
	}
	

}

线程和任务:

线程是去抢占CPU资源的,任务是具体执行的业务逻辑的,线程内部会包含一个任务,线程启动(start),当抢到资源之后,任务就开始执行了。

上述两种方式的区别:

1.MyThread,继承Thread类的方式,直接在类中重写run方法,使用的时候,直接实例化MyThread,start即可,因为Thread内部存在Runnable。

2.MyRunnable,实现Runnable接口的方法,在实现类中重写run方法,使用的时候,需要先创建Thread对象,并将MyRunnable注入到Thread中,再调用Thread.start()方法。

可以这样理解,Thread失去抢占CPU资源的,而Runnable是执行任务的。
实际开发中推荐第二种方式(低耦合)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

spider-clown

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值