Java多线程
线程的创建
1.继承Thread
2.实现Runnable
3.实现Callable
使用继承Thread类来开发多线程的应用程序在设计上是有局限性的,因为Java是单继承。
继承Thread类
public class ThreadDemo1 { // 继承Thread类 写法1 static class MyThread extends Thread { @Override public void run () { //要实现的业务代码 } } // 写法2 Thread thread = new Thread (){ @Override public void run () { //要实现的业务代码 } }; }实现Runnable接口
//实现Runnable接口 写法1 class MyRunnable implements Runnable { @Override public void run () { //要实现的业务代码 } } //实现Runnable接口 写法2 匿名内部类 class MyRunnable2 { public static void main ( String [] args ) { Thread thread = new Thread ( new Runnable () { @Override public void run () { //要实现的业务代码 } }); } }实现Callable接口(Callable + FutureTask 创建带有返回值的线程)
package ThreadDeom ; import java . util . concurrent . Callable ; import java . util . concurrent . ExecutionException ; import java . util . concurrent . FutureTask ; /** * user:ypc; * date:2021-06-11; * time: 17:34; */ //创建有返回值的线程 Callable + Future public class ThreadDemo2 { static class MyCallable implements Callable < Integer >{ @Override public Integer call () throws Exception { return 0 ; } } public static void main ( String [] args ) throws ExecutionException , InterruptedException { //创建Callable子对象 MyCallable myCallable = new MyCallable (); //使用FutureTask 接受 Callable FutureTask < Integer > futureTask = new FutureTask <>( myCallable ); //创建线程并设置任务 Thread thread = new Thread ( futureTask ); //启动线程 thread . start (); //得到线程的执行结果 int num = futureTask . get (); } }也可以使用lambda表达式
class ThreadDemo21 { //lambda表达式 Thread thread = new Thread (()-> { //要实现的业务代码 }); }Thread的构造方法
线程常用方法
获取当前线程的引用、线程的休眠
class Main { public static void main ( String [] args ) throws InterruptedException { Thread . sleep ( 1000 ); //休眠1000毫秒之后打印 System . out . println ( Thread . currentThread ()); System . out . println ( Thread . currentThread (). getName ()); } }package ThreadDeom ; /** * user:ypc; * date:2021-06-11; * time: 18:38; */ public class ThreadDemo6 { public static void main ( String [] args ) throws InterruptedException { Thread thread = new Thread ( new Runnable () { @Override public void run () { System . out . println ( "线程的ID:" + Thread . currentThread (). getId ()); System . out . println ( "线程的名称:" + Thread . currentThread (). getName ()); System . out . println ( "线程的状态:" + Thread . currentThread (). getState ()); try { Thread . sleep ( 1000 ); } catch ( InterruptedException e ) { e . printStackTrace (); } } }, "线程一" ); thread . start (); Thread . sleep ( 100 ); //打印线程的状态 System . out . println ( "线程的状态:" + thread . getState ()); System . out . println ( "线程的优先级:" + thread . getPriority ()); System . out . println ( "线程是否存活:" + thread . isAlive ()); System . out . println ( "线程是否是守护线程:" + thread . isDaemon ()); System . out . println ( "线程是否被打断:" + thread . isInterrupted ()); } }
线程的等待
假设有一个坑位,thread1 和 thread2 都要上厕所。一次只能一个人上,thread2只能等待thread1使用完才能使用厕所。就可以使用join()方法,等待线程1执行完,thread2在去执行。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did214578