高级功能-多线程 多线程是实现多任务的一种方式
(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()); } }