【多线程】初总结

首先是先了解:

  • 线程与进程:进程是资源分配的基本单位,线程是调度的基本单位。进程包含线程,线程共用进程的资源。
  • 线程与进程区别:简单来说进程可以看作一个应用,线程是在进程中执行的一个任务;线程是进程的子集,一个程序至少有一个进程,一个进程至少有一个线程;不同的进程使用不同的内存空间,而所有的线程共享一片相同的内存空间。
    #多线程的实现:
  • 继承Thread类:
class MyThread extends Thread{//线程的主体类
	
	private String title;
	public MyThread(String title) {
		this.title = title;
	}
	@Override
	public void run() {//线程的主体方法
		for(int i = 0; i < 10; i++) {
			System.out.println(this.title+"运行:i="+i);
		}
	}
}
public class test1 {
	public static void main(String[] args) {
		new MyThread("线程A").start();
		new MyThread("线程B").start();
		new MyThread("线程C").start();

	}
}
  • 实现Runnable接口
class MyThread1 implements Runnable{//线程的主体类
	private String title;
	public MyThread1(String title) {
		this.title = title;
	}
	@Override
	public void run() {//线程的主体方法
		for(int i = 0; i < 10; i++) {
			System.out.println(this.title+"运行1:i="+i);
		}
	}
}
public class test2 {
	public static void main(String[] args) {
//		Thread threadA = new Thread(new MyThread1("线程对象A"));
//		Thread threadB= new Thread(new MyThread1("线程对象B"));
//		Thread threadC = new Thread(new MyThread1("线程对象C"));
//		threadA.start();
//		threadB.start();
//		threadC.start();
		for(int x=0;x<3;x++) {
			String title = "线程对象-"+x;
			new Thread(()->{
				for(int y=0;y<10;y++) {
					System.out.println(title+"运行:y="+y);
				}
			}).start();;
		}
	}
}

要记住要调用 Thread.start() 方法才会启动线程,如果直接调用 Thread . run() 方法,就只会和普通的方法一样。

那问题来了:是用Thread还是Runnab呢?这个就看你的是否要调用其他类,因为在java中是没有多继承的,所以使用Runnable就好了!文本样式

多线程的拓展:

  1. 线程的命名:new Thread(mt,"线程对象").start();
  2. 线程休眠:Thread.sleep(1000);
  3. 线程中断:Thread thread = new Thread();thread.interrupt();
  4. 线程的强制执行:Thread mainthread = Thread.currentThread();mainthread.join();
  5. 线程的礼让:Thread.yield();
  6. 当前线程:Thread.currentThread().getName()
  7. 设置线程优先级:threadA.setPriority(Thread.MAX_PRIORITY); threadB.setPriority(Thread.MIN_PRIORITY); threadC.setPriority(Thread.NORM_PRIORITY);(主线程一般都是5,即NORM_PRIORITY)
  8. synchronized:同步方法(相当于上锁),public synchronized boolean sale() {}
  9. wait():导致线程进入等待状态,直到它被其他线程通过notify()或者notifyAll唤醒,该方法只能在同步方法中调用。
  10. notify():唤醒线程
  11. notifyAll():唤醒所有线程
  12. volatile 关键字:主要在属性上使用 ,绕过数据属性,直接使用内存的操作。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值