java零基础的坎坷之路【53】——多线程概述

1、进程:系统资源调度和分配的最小单位。

2、线程:进程中的某个执行路径。

3、并行和并发的区别:
	并行:逻辑上同时发生,一段时间内同时发生
	并发:物理上同时发生,一个时间点同时发生
	
4、实现多线程的方式:
	方式一、自定义MyThread类继承Thread类,重写Thread类的run方法
		例如:
			public class MyThread1 extends Thread {
				@Override
				public void run() {
					for (int i = 0; i < 5; i++) {
						System.out.println(Thread.currentThread().getName()+"这是线程"+i);
					}
				}
			}
			
			public class demo1 {
				public static void main(String[] args) {
					MyThread1 mt1 = new MyThread1();
					MyThread1 mt2 = new MyThread1();
					mt1.start();
					mt2.start();
				}
			}
			
		①、继承了Thread类的自定义MyThread类的成员方法:
			public final String getName():获取线程的名称
			public final String setName():设置线程的名称
			
		②、如果当前类不是THread类的子类:
			public static Thread currentThread():返回正在执行的线程对象
			Thread.currentThread.getName()
		
		③、线程优先级
			public final int getPriority():获取线程的优先级
			public final void setPriority(int newPriority):设置线程的优先级
			
			注意:
				线程默认优先级:5
				线程优先级的范围:1-10
				线程优先级仅仅表示线程获取CPU时间片的几率大而已!
	方式二、自定义MyThread类实现Runnable接口,重写Runnable接口的run方法
		例如:
			public class MyThread2 implements Runnable {
				@Override
				public void run() {
					for (int i = 0; i < 4; i++) {
						System.out.println(Thread.currentThread().getName()+"这是线程"+i);
					}
				}
			}
			
			public class demo2 {
				public static void main(String[] args) {
					MyThread2 mt1 = new MyThread2();
					MyThread2 mt2 = new MyThread2();
					Thread t1 = new Thread(mt1,"柳岩");
					Thread t2 = new Thread(mt2,"徐冬冬");
					t1.start();
					t2.start();
				}
			}
		
		
	
5、线程的控制
	public static void sleep(long milis):线程休眠
	public final void join():线程加入
	public static void yield():线程礼让
	public final void setDaemon(boolean on):后台线程
	public void interrupt():线程中断

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

明致成

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

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

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

打赏作者

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

抵扣说明:

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

余额充值