java多线程

多线程可以实现多个任务同时并发执行。

线程:进程中负责程序执行的执行单元
线程本身依靠程序进行运行
线程是程序中的顺序控制流,只能使用分配给程序的资源和环境

多线程的实现方法

必须使用start()方法启动线程。

1.继承Thread类,必须覆写run()方法。

2.实现Runnable接口,必须覆写run()方法,同时一般需要继承Thread类中的start()方法启动线程,因为Runnable是接口(特殊抽象类),接口中只具有抽象方法。

因为多线程的任务是竞争处理器资源进行处理,如果有实现的顺序的要求,必须对不同的线程进行加锁。

匿名内部类必须存在于接口或抽象类的基础上

继承Thread类

package *;

class A extends Thread{
	public void run() {
		for (int i = 0; i <100; i++) {
			System.out.println("人之初"+i);
		}
	}
}
class B extends Thread{
	public void run() {
		for (int i = 0; i <100; i++) {
			System.out.println("性本善"+i);
		}
	}
}
public class San {
	public static void main(String[] args) {
		new A().start();
		new B().start();
	}
}

  运行结果

实现Runnable接口

package *;

class X implements Runnable{
//接口要继承runnable里面的start方法
	@Override//注解:准确覆写
	public void run() {
		for (int i = 0; i <100; i++) {
			System.out.println("你好"+i);
		}
	}
	
}
class Y implements Runnable{

	@Override
	public void run() {
		for (int i = 0; i <100; i++) {
			System.out.println("世界"+i);
		}
	}
	
}

public class Yi {
	public static void main(String[] args) {
		X x=new X();
		new Thread(x).start();
		new Thread(new Y()).start();
	}
}

  运行结果

 匿名内部类方法

package *;

public class Si {
	public static void main(String[] args) {
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i <100; i++) {
					System.out.println("和尚念经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t1").start();
		
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 100; i++) {
					System.out.println("道士讲经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t2").start();
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 100; i++) {
				System.out.println("和尚念经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t3").start();
		
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i <100; i++) {
					System.out.println("道士讲经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t4").start();
		
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i <100; i++) {
				System.out.println("和尚念经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t5").start();
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 100; i++) {
					System.out.println("道士讲经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t6").start();
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i < 100; i++) {
					System.out.println("和尚念经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t7").start();
		new Thread(new Runnable() {
			public void run() {
				for (int i = 0; i <100; i++) {
					System.out.println("道士讲经"+Thread.currentThread().getName()+" "+i);
				}
			}
		},"t8").start();
	}
}
原文地址:https://www.cnblogs.com/dldrjyy13102/p/7643613.html