Java创建线程的几种方式

学习笔记 Java教程-廖雪峰

Java创建线程

Thread thread = new Thread(); // 创建线程
thread.start(); // 启动新线程
线程状态
	New:新创建的线程,尚未执行;
	Runnable:运行中的线程,正在执行run()方法的Java代码;
	Blocked:运行中的线程,因为某些操作被阻塞而挂起;
	Waiting:运行中的线程,因为某些操作在等待中;
	Timed Waiting:运行中的线程,因为执行sleep()方法正在计时等待;
	Terminated:线程已终止,因为run()方法执行完毕。

创建线程的几种方式

1、new Thread();线程的run()方法未被覆写,没有实际操作即结束了线程

Thread thread = new Thread(); // 创建线程
// System.out.println("thread.getState()=" + thread.getState()); //打印线程状态, NEW
thread.start(); // 启动线程
// System.out.println("thread.getState() -> " + thread.getState()); //打印线程状态,TERMINATED

2、从Thread派生一个自定义类,然后覆写run()方法

	/**
	 *  继承Thread,覆写run() 方法
	 */
	public static void createThread2() {
		Thread thread = new MyThreadTest();
		thread.start(); // 启动新线程
		thread.run(); // 注意:直接调用run()不会创建新的线程
	}
// 从Thread派生一个自定义类,然后覆写run()方法
class MyThreadTest extends Thread {
    @Override
    public void run() {
        System.out.println("see: MyThreadTest extends Thread!");
    }
}

3、创建Thread实例时,传入一个Runnable实例

	/**
	 *  创建Thread实例时,传入一个Runnable实例
	 */
	public static void createThread3() {
		Thread thread = new Thread(new MyRunnableTest());
		thread.start(); // 启动新线程
	}
// 实现Runnable
class MyRunnableTest implements Runnable {
    @Override
    public void run() {
        System.out.println("see: MyRunnableTest implements Runnable!");
    }
}

4、匿名内部类实现Runnable

	/**
	 * 匿名内部类
	 */
	public static void createThread4() {
		Thread thread = new Thread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					System.out.println("new Runnable() - start");
					System.out.println("new Runnable() - end");
				}
		});
		// Java8引入的lambda语法进一步简写
		Thread t = new Thread(() -> {
            System.out.println("since java 8, lambda ");
        });
        t.start(); // 启动新线程
	}

测试用例

public class ThreadTest {
	public static void main(String[] args) throws InterruptedException {
//		threadState();
		createThread4();
	}
	
	/**
	 *  创建线程,执行但没有操作
	 */
	public static void createThread1() {
		Thread thread = new Thread();
		thread.start(); // 启动新线程
	}

	/**
	 *  继承Thread,覆写run() 方法
	 */
	public static void createThread2() {
		Thread thread = new MyThreadTest();
		thread.start(); // 启动新线程
		thread.run(); // 注意:直接调用run()不会创建新的线程
	}
	
	/**
	 *  创建Thread实例时,传入一个Runnable实例
	 */
	public static void createThread3() {
		Thread thread = new Thread(new MyRunnableTest());
		thread.start(); // 启动新线程
	}

	/**
	 * Java8引入的lambda语法进一步简写
	 */
	public static void createThread4() {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				System.out.println("new Runnable() - start");
				System.out.println("new Runnable() - end");
			}
		});
		thread.start();
		
		Thread t = new Thread(() -> {
            System.out.println("since java 8, lambda ");
        });
        t.start(); // 启动新线程
	}
	
	/**
	 * 创建的新线程与当前线程同时运行,但调度顺序由操作系统决定
	 * @throws InterruptedException 
	 */
	public static void createThread5() throws InterruptedException {
		System.out.println("<---start------------------------createThread5--------------------------->");
		Thread t = new Thread(() -> {
			try {
				Thread.sleep(30);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            System.out.println("start a new Thread ");
            System.out.println("since java 8, lambda ");
        });
        t.start(); // 启动新线程,新线程与当前线程同时运行,但调度顺序由操作系统决定
        Thread.sleep(30); // 在线程中调用Thread.sleep(),强迫当前线程暂停一段时间
		System.out.println("<---end------------------------createThread5--------------------------->");
	}
	
	/**
	 * 线程的更多操作 Thread.sleep(xx)休眠/暂停/等待 ;Thread.setPriority(1~10)优先级 低~高
	 * @throws InterruptedException 
	 */
	public static void createThread6() throws InterruptedException {
		int times = 5;
		Thread thread = new Thread(() -> {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (int i = 0; i < times; i++) {
				System.out.println("show your num, num is " + times);
			}
		});
		
		Thread thread2 = new Thread(() -> {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			for (int i = 0; i < times; i++) {
				System.out.println("Second Thread, num is " + times);
			}
		});
		
		thread.start();
//		thread.join(); // 等待线程thread完成后继续执行 或者 join(1000) 等待1000毫秒后继续执行
//		thread.start(); 同一个线程对象只能start()一次
		thread2.start();
		thread.setPriority(1);
		thread2.setPriority(10);
	}
	
	/**
New:新创建的线程,尚未执行;
Runnable:运行中的线程,正在执行run()方法的Java代码;
Blocked:运行中的线程,因为某些操作被阻塞而挂起;
Waiting:运行中的线程,因为某些操作在等待中;
Timed Waiting:运行中的线程,因为执行sleep()方法正在计时等待;
Terminated:线程已终止,因为run()方法执行完毕。
	 * @throws InterruptedException
	 */
	public static void threadState() throws InterruptedException {
		Thread thread = new Thread(() -> {
			System.out.println("start thread -------------------");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("end thread -------------------------");
		});
		System.out.println("thread.getName()=" + thread.getName());
		System.out.println("thread.getPriority()=" + thread.getPriority());
		System.out.println("thread.getThreadGroup()=" + thread.getThreadGroup());
		System.out.println("thread.getState()=" + thread.getState());
		System.out.println(thread.getState());
		thread.start();
		System.out.println("thread.start() -> " + thread.getState());
		Thread.sleep(200);
		System.out.println("thread.start() -> " + thread.getState());
		thread.join();
		System.out.println("thread.join() -> " + thread.getState());
		
		/*
		thread.wait();
		System.out.println("thread.wait() -> " + thread.getState());
		thread.notify();
		System.out.println("thread.notify() -> " + thread.getState());
		*/
	}
	
}

// 从Thread派生一个自定义类,然后覆写run()方法
class MyThreadTest extends Thread {
    @Override
    public void run() {
        System.out.println("see: MyThreadTest extends Thread!");
    }
}

// 实现Runnable
class MyRunnableTest implements Runnable {
    @Override
    public void run() {
        System.out.println("see: MyRunnableTest implements Runnable!");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值