内网IM如何打破“部门墙”
2026/7/23 15:14:04
1. 继承Thread类创建线程
public class Thread1 extends Thread { public void run() { System.out.println(Thread.currentThread().getName() + " is running..."); } public static void main(String[] args) { Thread1 thread1 = new Thread1(); thread1.setName("thread-1"); thread1.start(); } }2. 实现Runnable接口创建线程
public class Thread2 implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running..."); } public static void main(String[] args) { Thread2 thread2 = new Thread2(); new Thread(thread2,"thread-2").start(); } }3. 使用Callable和Future创建线程
public class Thread3 implements Callable { @Override public Object call() throws Exception { int i = 0; for (; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "-" + i); } return i; } public static void main(String[] args) { Thread3 thread3 = new Thread3(); FutureTask futureTask = new FutureTask(thread3); new Thread(futureTask, "callThread").start(); try { System.out.println(futureTask.get()); // 获取返回值 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }4. 使用线程池创建
public class Thread4 { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(15); executorService.execute(new Thread5()); try { Future future = executorService.submit(new Thread6()); String result = (String) future.get(); // 获取返回值 System.out.println(result); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } executorService.shutdown(); } } class Thread5 implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " is running..."); } } class Thread6 implements Callable{ @Override public Object call() throws Exception { return "thread-6"; } }第3种,第4种,可以获取返回值。