高级功能-多线程

高级功能-多线程
多线程是实现多任务的一种方式

(1)线程名称由"Thread. currentThread(). getName();"获取。
(2)线程的开启要使用线程对象的start()方法,开启的新线程并发执行对象的run()方法。而直接调用线程对象的run0) 方法并不会开启新的线程。需要指出的是,调用了线程的run() 方法之后,该线程已经由新建状态改成运行状态,不需再次调用线程对象的start()方法, 否则将引发IllegalThreadStateExccption异常。
系统不停地在各个线程之间切换,每个线程只有在系统分配的时间内才能软得CPU的控制权。

package com.cs;

public class test {
	public static void main(String[] args) {
		Mythread mythread=new Mythread();
		Thread thread =new Thread(mythread);
		thread.setName("123");
		
		Mythread1 mythread1=new Mythread1();
		mythread1.setName("asd");
		mythread1.start();
		System.out.println("线程名称1:"+Thread.currentThread().getName());
		thread.start();
		System.out.println("线程名称2:"+Thread.currentThread().getName());

	}

}

在这里插入图片描述

多次运行结果不一样

在这里插入图片描述

package com.cs;

public class Mythread1 extends Thread{
	public void run(){
		System.out.println("歌曲下载1!");
	}
}

package com.cs;

public class Mythread implements Runnable{

	public void run(){
		System.out.println("歌曲下载!");
	}
}

PS:

package com.cs;

public class test {
	public static void main(String[] args) {
		Mythread a=new Mythread();
		Thread thread =new Thread(a);
		thread.setName("123");
		
		Mythread1 b=new Mythread1();
		b.setName("asd");
		b.start();
		System.out.println("线程名称1:"+Thread.currentThread().getName());
		thread.start();
		System.out.println("线程名称2:"+Thread.currentThread().getName());

	}

}

这样更加简单明了

发布了72 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/BOGEWING/article/details/102839588