Java多线程以及线程优先级

1 继承Thread类

多线程的实现

实现多线程只需要继承Thread类即可,重写run()方法,封装需要被线程执行的代码

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 11; i++) {
            System.out.println(i);
        }
    }
}
public class ThreadTest {
    public static void main(String[] args) {
    	Thread my1 = new MyThread();
        Thread my2 = new MyThread();
        Thread my3 = new MyThread();
		 
		my1.start();	// 启动线程,由JVM调用线程的run()方法
        my2.start();
        my3.start();
    }
}

获取和设置线程名称

使用getName()方法获取线程名称

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

使用setName()方法设置线程名称

my1.setName("HelloWorld");

线程优先级

getPriority() 返回线程优先级
setPriority() 设置线程优先级

  • 优先级由低到高为 1-10 , 默认值为 5
  • 线程优先级高仅仅表示线程获取CPU时间片的几率高
  • 并不一定会等优先级高的线程执行完了才去执行优先级低的线程
public class ThreadTest {
    public static void main(String[] args) {
    	Thread my1 = new MyThread();
        Thread my2 = new MyThread();
        Thread my3 = new MyThread();

		System.out.println(my1.getPriority());	//返回线程优先级

		my1.setPriority(10);	// 设置线程优先级
        my2.setPriority(5);
        my3.setPriority(1);
		 
		my1.start();	
        my2.start();
        my3.start();
    }
}

2 实现Runnable接口

虽然继承Thread类实现多线程非常简单,但是在实际开发中,java单继承这一特性使得我们在需要继承其他类的时候,多线程的实现就要依靠实现Runnable接口

public class MyRunnable implements Runnable {
	@override
	public void run() {		// 同样重写run()方法
		for (int i = 0; i < 20; i++) {
			System.out.println(Thread.currentThread().getName() + " " + i);
		}
	}
}
/**
 * 创建MyRunnable类的对象
 * 创建Thread类的对象,将MyRunnable对象作为构造方法的参数
 */
public class MyRunnableTest {
	public static void main(String[] args) {
        Runnable r1 = new MyRunnable();

        Thread t1 = new Thread(r1, "hello");	// 可以直接设置线程名称
        Thread t2 = new Thread(r1, "world");

        t1.start();
        t2.start();
    }
}

方法2总结

  • 没有继承Thread类,如果有需求可以继承其他类
  • 适合多个相同程序的代码去处理同一个资源的情况,把线程和程序的代码、数据有效分离

3 实现Callable接口

  • 重写call()方法
  • 好处:有返回值,允许抛异常

4 使用线程池

  • 减少创建新线程的时间,重复利用线程池中的线程,降低资源消耗,可有返回值。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值