JAVA–Thread/Runnable_线程

实现多线程有两种方式,第一种是继承Thread类,第二种是实现Runnable接口
线程之间不互相影响,各自独立运行

一、继承Thread类

  • 首先要写一个类,继承Thread类,在他的run方法中书写要进行的操作
  • 调用该线程时,只需实例化这个类,并调用它的start()方法
//内部类
class MusicThread extends Thread{

	public void run() {
		for(int i = 0;i<50;i++){
			System.out.println("听听歌"+ i);
		}
	}
	
}
public class ThreadDemo {
	
	public static void main(String[] args) {
		//开始看电影
		for(int i = 0;i < 50;i++){
			System.out.println("看电影"+ i);
			if(i == 10){
				//当看电影到10的时候开始启动听歌线程
				MusicThread t = new MusicThread();
				t.start();
			}
		}
	}
}

二、实现Runnable接口

  • 写一个类实现Runnable接口,在run()方法中书写要进行的操作

  • 调用时实例化一个Thread对象和自己写的Runnable对象,再通过Thread的构造函数把Runnable对象添加到Thread中实现,再通过Thread的start()方法执行线程

    class MusicRunnable implements Runnable{ 
          	public void run() {
          		for(int i = 0;i<50;i++){
          			System.out.println("放歌"+ i);
          		}
          	}
          }
          
          public class RunnableThread {
          	public static void main(String[] args) {
          		//开始看电影
          		for(int i = 0;i < 50;i++){
          			System.out.println("看电影"+ i);
          			if(i == 10){
          			//当看电影到10的时候开始启动听歌线程
          				Runnable t1 = new MusicRunnable();
          				Thread t = new Thread(t1);
          				t.start();
          			}
          		}
          	}   
          }
    

注意点:
继承Thread的线程类,每个线程都会执行一次该类的所有方法,而实现Runnable接口的线程可以让多个线程使用同一对象。

例如:
1.每个人吃50个苹果,继承Thread的线程类,每个线程都会执行一次该类的所有方法

class Person extends Thread{
	private int n = 50;
	public Person(String name){
		super(name);
	}
	public void run(){
		for (int i = 0;i < n;i ++){
			System.out.println(super.getName() + "吃了一个苹果,他还剩" + (n-i-1) + "苹果");
		}
	}
}
public class EatAppleByExtend {

	public static void main(String[] args) {
		//直接new Person
		new Person("СA").start();
		new Person("СB").start();
		new Person("СC").start();
	}

}

JAVA--Thread/Runnable_线程
2.通过Runnable接口实现线程对象,三个人一共吃50个苹果

class Apple implements Runnable{
	private int n = 50;
	public void run(){
		for (int i = 0;i < 50;i ++){
			if (n > 0){
				System.out.println(Thread.currentThread().getName() + "吃了编号为" + n-- + "的苹果");
			}
		}
	}
}

public class EatAppleByImplements {

	public static void main(String[] args) {
		//new一个实现Runnable接口的Apple对象a
		Apple a= new Apple();
		//new三个线程对象,每个线程对象都调入对象参数a
		new Thread(a,"СA").start();
		new Thread(a,"СB").start();
		new Thread(a,"СC").start();

	}

}

JAVA--Thread/Runnable_线程

相关文章:

  • 2021-10-06
  • 2021-10-10
  • 2021-09-15
  • 2021-05-18
  • 2021-06-15
  • 2022-02-09
  • 2021-12-30
  • 2021-04-10
猜你喜欢
  • 2021-09-09
  • 2021-06-22
  • 2021-11-25
  • 2021-07-21
  • 2021-06-03
  • 2021-10-23
  • 2021-08-30
相关资源
相似解决方案