当前位置: 代码迷 >> 综合 >> 多线程学习(二) 多线程创建方式--4种
  详细解决方案

多线程学习(二) 多线程创建方式--4种

热度:19   发布时间:2023-10-17 19:01:07.0

1.继承thread(重写run)

public class ThreadDemo {public static void main(String[] args) {TestThread t1 = new TestThread("thread1");TestThread t2 = new TestThread("thread2");t1.start();t2.start();}
}class TestThread extends Thread {String name;public TestThread(String name) {this.name = name;}@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(this.name + ":" + i);}}
}

Thread的run和start有什么区别

run()方法:

  是在主线程中执行方法,和调用普通方法一样;(按顺序执行,同步执行)

start()方法:

  是创建了新的线程,在新的线程中执行;(异步执行)

2.实现runnable(重写run)

package test;public class RunnableDemo {public static void main(String[] args) {TestRunnable r1 = new TestRunnable("runnable-1");TestRunnable r2 = new TestRunnable("runnable-2");r1.start();r2.start();}
}class TestRunnable implements Runnable {String name;Thread thread;public TestRunnable(String name) {this.name = name;}@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(this.name + ":" + i);}}public void start() {System.out.println("Starting " + this.name);if (thread == null) {thread = new Thread(this, this.name);thread.start();}}
}

3.匿名内部类(重写run)

package test;public class test3 {public static void main(String[] args) {System.out.println("-----多线程创建开始-----");Thread thread = new Thread(new Runnable() {public void run() {for (int i = 0; i< 100; i++) {System.out.println("i:" + i);}}});Thread thread2 = new Thread(new Runnable() {public void run() {for (int i = 0; i< 100; i++) {System.out.println("j:" + i);}}});thread.start();thread2.start();System.out.println("-----多线程创建结束-----");}}

4.Callable(重写run)

package test;import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;/*** callable*/
public class CallableDemo {static class MyThread implements Callable<String> {@Overridepublic String call() throws Exception {return "Hello world";}}static class MyRunnable implements Runnable {@Overridepublic void run() {}}public static void main(String[] args) {ExecutorService threadPool = Executors.newSingleThreadExecutor();Future<String> future = threadPool.submit(new MyThread());try {System.out.println(future.get());} catch (Exception e) {} finally {threadPool.shutdown();}}
}
  相关解决方案