package org.study.thread;

/**
 * 启动一个线程的3种方式
 */
public class TraditionalThread {

	public static void main(String[] args) {
		// 1. 继承自Thread类(这里使用的是匿名类)
		new Thread(){
			@Override
			public void run() {
				while(true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("threadName: " + Thread.currentThread().getName());
				}
			};
		}.start();
		
		// 2. 实现Runnable接口(这里使用的是匿名类)
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("threadName: " + Thread.currentThread().getName());
				}
			}
		}).start();
		
		// 3.即实现Runnable接口,也继承Thread类,并重写run方法
		new Thread(new Runnable() {
			@Override
			public void run() {	// 实现Runnable接口
				while(true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("implements Runnable thread: " + Thread.currentThread().getName());
				}
			}
		}) {	// 继承Thread类
			@Override
			public void run() {
				while(true) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("extends Thread thread: " + Thread.currentThread().getName());
				}
			}
		}.start();
	}
}


执行结果:

threadName: Thread-0

threadName: Thread-1

extends Thread thread: Thread-2

threadName: Thread-1

threadName: Thread-0

extends Thread thread: Thread-2

threadName: Thread-1

threadName: Thread-0

extends Thread thread: Thread-2

。。。


相关文章:

  • 2022-12-23
  • 2022-01-01
  • 2021-05-28
  • 2021-06-10
  • 2021-06-28
  • 2022-12-23
  • 2022-12-23
  • 2022-02-09
猜你喜欢
  • 2022-12-23
  • 2021-06-01
  • 2021-09-27
  • 2022-01-21
  • 2022-01-23
  • 2021-11-26
  • 2021-08-03
相关资源
相似解决方案