java高级--多线程初体验

1、主线程

    main()方法即为主线程入口 产生其他子线程的线程 必须最后完成执行,因为他执行各种关闭动作
public static void main(String args[]) throws IOException, ClassNotFoundException{
		//获取当前线程对象
		Thread thread = Thread.currentThread();
		//获取当前线程名字
		String name = thread.getName();
		System.out.print(name);
		//设置当前线程名字
		thread.setName("song");
		System.out.print(thread.getName());
	}

2、如何通过集成Thread类创建线程

    2.1、继承Thread 一定要重写run()方法 创建线程对象,调用start()方法启动线程 public void run(){ for(int i=0;i<100;i++){ System.out.println(Thread.currentThread().getName()+":"+i); } } public static void main(String args[]) throws IOException, ClassNotFoundException{ Text01 one = new Text01(); Text01 two = new Text01(); one.start(); //不能直接调用run()方法:只有主线程一个执行路径,一次调用了两次run()方法 two.start(); } 2.2、实现Runnable接口 实现run()方法,编写线程执行体 调用start()方法
public class Text01 implements Runnable{
	
	public void run(){
		for(int i=0;i<100;i++){
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
	}
	public static void main(String args[]) throws IOException, ClassNotFoundException{
		Runnable run = new Text01();
		Thread thread = new Thread(run,"mythread1");
		Thread thread2 = new Thread(run,"mythread2");
		thread.start();
		thread2.start();
	}
}

3、这两种创建线程的方法有什么区别

    一个继承类,一个实现接口必须重写run方法 继承只能继承一个 继承Thread类 编写简单,可直接操作线程 适用于单继承 实现Runnable接口 避免单继承局限性 便于共享资源

4、如何选择用哪个方式

    Thread是多个线程分别完成自己的任务,Runnable是多个线程共同完成一个任务
经验分享 程序员 微信小程序 职场和发展