1.java线程
Java 线程
方式1
继承Thread /* * 多线程的创建:方式一:继承Thread类 * 1.创建一个继承于Thread的子类 * 2.重写Thread 类的run() -->将此线程执行的操作申明在run()中 * 3.创建Thread类的子类的对象 * 4.通过此对象调用start() 5.注意 : 要想启动多个线程,可以new 多个对象,在调用start()方法 * */ public class TreadTest { public static void main(String[] args) { MyTread t = new MyTread(); t.start(); System.out.println("hello"); } } class MyTread extends Thread{ @Override public void run() { for (int i=0;i<100;i++){ if (i%2==0){ System.out.println(i); } } } }
方式2
import jdk.nashorn.internal.ir.WhileNode; public class ThreadTest2 { public static void main(String[] args) { Window w = new Window(); Thread t1 = new Thread(w); Thread t2= new Thread(w); Thread t3= new Thread(w); t1.setName("窗口1"); t2.setName("窗口2"); t3.setName("窗口3"); t1.start(); t2.start(); t3.start(); } } class Window implements Runnable{ private int ticket=100; @Override public void run() { while (ticket>0){ ticket--; System.out.println(Thread.currentThread().getName()+":"+ticket); } } } 比较创建多线程的两种方式: 1.优先选择实现Runnable接口的方式。 2. 如果多个线程有共享数据,选Runnable,天然实现共享数据功能。
方式3
实现Callalbe接口,优点:
1. call()可以有返回值的
2. 可以抛出异常
import jdk.nashorn.internal.codegen.CompilerConstants; import sun.misc.PostVMInitHook; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; //1.创建一个实现callable接口的实现类 class TestThead implements Callable { // 2. 重写 call() 方法 @Override public Object call() throws Exception { int sum = 0; for (int i=0;i<100;i++){ if (i %2==0){ System.out.println(i); sum+=i; } } // Callable 有返回值 return sum; } } public class NewThread3 { public static void main(String[] args) throws ExecutionException, InterruptedException { // 3.实现callable接口实现类的对象 TestThead t = new TestThead(); // 4.创建FutureTask对象 FutureTask futureTask =new FutureTask(t); // 5.创建Thread对象,并调用start() 方法 new Thread(futureTask).start(); // 6. 获取返回值,Callalbe 中call()的返回值,调用get() 方法 try { Object sum = futureTask.get(); }catch (ExecutionException e){ e.printStackTrace(); } } }
方式4
线程池
import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; public class NewThread4 { public static void main(String[] args) { //1.提供指定线程数的线程池 ExecutorService service = Executors.newFixedThreadPool(10); // ThreadPoolExecutor service1 = (ThreadPoolExecutor) service; // service1.setCorePoolSize(8); //2. 线程指定线程操作,需要实现Callable 或Runnable接口实现类的对象 service.execute(new TestThread4());// Runnable 方式 // service.submit(new TestThread4());// Callable 方式 // 关闭连接池 service.shutdown(); } } class TestThread4 implements Runnable{ @Override public void run() { int sum =0; for(int i =0;i<100;i++){ if(i%2==0){ System.out.println(i); sum+=i; } } System.out.println("总和为:"+sum); } }
有疑问可以加wx:18179641802,进行探讨