JAVA 多线程

什么是多线程

如果在一个进程中同时运行了多个线程,用来完成不同的工作,则称之为“多线程” 如果在一个进程中同时运行了多个线程,用来完成不同的工作,则称之为“多线程”

多个线程交替占用CPU资源,而非真正的并行执行 多个线程交替占用cpu资源,而非真正的并行执行

多线程的好处

充分利用CPU的资源简化编程模型、 充分利用cpu的资源简化编程模型、带来良好的用户体验 带来良好的用户体验

Thread类

Java提供了java.lang.Thread类支持多线程编程

主线程

main()方法即为主线程入口产生其他子线程的线程 Main()方法即为主线程入口

产生其他子线程的线程

必须最后完成执行,因为它执行各种关闭动作 必须最后完成执行,因为它执行各种关闭动作

 线程中的方法

public class ThreadDemo01 {

	public static void main(String[] args) {
		// main()方法是程序的主入口,是一个线程
		// currentThread():获取当前线程对象
		Thread thread = Thread.currentThread();
		// getName():获取当前线程的名称
		String name = thread.getName();
		System.out.println(name);
		// getPriority():获取当前线程的优先级
		int priority = thread.getPriority();
		System.out.println("当前线程的优先级:" + priority);
		// setName():设置线程的名称
		thread.setName("尼古拉斯赵四");
		System.out.println("线程名称:" + thread.getName());
		// setPriority():设置线程优先级
		thread.setPriority(8);
		System.out.println("线程优先级:" + thread.getPriority());

		System.out.println("线程优先级最高值:" + Thread.MAX_PRIORITY);// 10
		System.out.println("线程优先级最低值:" + Thread.MIN_PRIORITY);// 1
		System.out.println("线程优先级默认值:" + Thread.NORM_PRIORITY);// 5
	}

}

接口方式创建线程

// 接口方式
public class MyThreadImp implements Runnable {
	@Override
	public void run() {
		// 在重写的run()方法中编写你要执行的代码:使用循环输出1-10
		for (int i = 1; i <= 10; i++) {
			System.out.println(Thread.currentThread().getName() + ">" + i);
		}

	}
}

继承方式创建线程

// 继承方式
public class MyThread extends Thread {
	// 无参构造
	public MyThread() {
	}

	// 有参构造
	public MyThread(String name) {
		super(name);
	}

	@Override
	public void run() {
		// 在重写的run()方法中编写你要执行的代码:使用循环输出1-10
		for (int i = 1; i <= 10; i++) {
			System.out.println(Thread.currentThread().getName() + ">" + i);
		}
	}
}

测试类

public class Test {

	public static void main(String[] args) {
		// 继承方式
		// 创建线程类对象
		MyThread mt1 = new MyThread("第一条线程");
		MyThread mt2 = new MyThread("第二条线程");
		// start()方法是启动线程的方法
		mt1.start();
		mt2.start();
		// 当同时启动两个线程以后,会出现两个线程交替占用CPU执行代码的结果
		
		
		// 接口方式
		MyThread mt = new MyThread();
		Thread thread1 = new Thread(mt, "第三条线程");
		Thread thread2 = new Thread(mt, "第四条线程");
		// start()方法是启动线程的方法
		thread1.start();
		thread2.start();
	}

}

运行结果

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值