多线程
多线程
创建线程的方法
-
继承Thread类,重写run方法,线程启动调用start方法
class MThread extends Thread { @Override public void run() { for (int i = 0; i < 100; i++) { if (i % 2 == 0) { System.out.println(Thread.currentThread().getName() + ":" + i); } } } } public class ThreadTest1 { public static void main(String[] args) { MThread m1 = new MThread(); m1.start(); for (int i = 0; i < 100; i++) { if (i % 2 != 0) { System.out.println(Thread.currentThread().getName() + ":" + i); }//main线程 } } }
-
实现Runable接口,重写run方法,作为参数传入Thread对象,线程启动调用start方法
class MRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 100; i++) { if (i % 2 == 0) { System.out.println(Thread.currentThread().getName() + ":" + i); } } } } public class ThreadTest2 { public static void main(String[] args) { MRunnable mThread = new MRunnable(); Thread thread = new Thread(mThread); thread.start(); for (int i = 0; i < 100; i++) { if (i % 2 != 0) { System.out.println(Thread.currentThread().getName() + ":" + i); }//main线程 } } }
-
实现Callable接口,重写call方法,作为参数传入FutureTask对象,然后再作为参数传入Thread对象,线程启动调用start方法,可以使用FutureTask获取返回值
class MCallable implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("111111"); return 1; } } public class ThreadTest3 { public static void main(String[] args) throws ExecutionException, InterruptedException { MCallable mc = new MCallable(); FutureTask<Integer> ft = new FutureTask<>(mc); new Thread(ft, "t1").start(); System.out.println(ft.isDone());//轮询 System.out.println(ft.get());//阻塞 } }
-
线程池
线程同步的方法
-
synchronized:
修饰方法 :
修饰静态方法是给当前类加锁,会作用于类的所有对象实例 ,进入同步代码前要获得 当前 class 的锁。
修饰实例方法是给当前对象实例加锁,进入同步代码前要获得当前对象实例的锁。
修饰代码块:
对括号里指定的对象/类加锁:
synchronized(object)
表示进入同步代码库前要获得 给定对象的锁。synchronized(类.class)
表示进入同步代码前要获得 给定 Class 的锁
-
ReentrantLock:
Lock lock = new ReentrantLock(); new Thread(() -> { lock.lock(); try { ...... } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }, "t1").start();
使用顺序推荐:ReentrantLock > synchronized 同步代码块 > synchronized 同步方法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!