本文共 7792 字,大约阅读时间需要 25 分钟。
进程是操作系统资源分配和调度的基本单位,是程序执行的实体。在现代计算机中,进程是线程的容器,线程则是程序的基本执行单元。
多线程技术通过将一个进程拆分为多个片段,利用多核CPU资源,提升任务处理效率。每个片段(线程)可以独立执行任务,并共享同一进程内存资源。
Java程序运行时,JVM启动一个进程,并在其内启动主线程。JVM自身也是多线程的,至少包含主线程和垃圾回收线程。
实现多线程有两种主要方式:通过继承Thread类或实现Runnable接口。
Thread类public class MyThread extends Thread { public MyThread() {} public MyThread(String name) { super(name); } @Override public void run() { for (int x = 0; x < 100; x++) { System.out.println(getName() + ":" + x); } }}public class MyThreadDemo { public static void main(String[] args) { MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); myThread1.setName("Tom"); myThread2.setName("Jack"); myThread1.start(); myThread2.start(); }} Runnable接口public class MyRunnable implements Runnable { @Override public void run() { for (int x = 0; x < 10; x++) { System.out.println(Thread.currentThread().getName() + ":" + x); } }}public class MyRunnableDemo { public static void main(String[] args) { MyRunnable my = new MyRunnable(); Thread thread1 = new Thread(my); Thread thread2 = new Thread(my); thread1.setName("Tom"); thread2.setName("Jack"); thread1.start(); thread2.start(); }} Callable接口允许方法返回值,并适用于ExecutorService的提交任务。
import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;class MyCallable implements Callable { @Override public Object call() throws Exception { for (int x = 0; x < 50; x++) { System.out.println(Thread.currentThread().getName() + ":" + x); } return null; }}public class CallableDemo { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(2); pool.submit(new MyCallable()); pool.submit(new MyCallable()); pool.shutdown(); }} Java采用抢占式调度,线程执行时间片轮转。线程优先级越高,执行概率越高,但不保证一定先执行。
线程控制包括线程的睡眠、加入和礼让等操作。
import java.util.Date;public class ThreadSleep extends Thread { @Override public void run() { for (int x = 0; x < 20; x++) { System.out.println(getName() + ":" + x + ",Date:" + new Date()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }}public class ThreadSleepDemo { public static void main(String[] args) { ThreadSleep Aa = new ThreadSleep(); ThreadSleep Bb = new ThreadSleep(); ThreadSleep Cc = new ThreadSleep(); Aa.setName("Tom"); Bb.setName("John"); Cc.setName("Jack"); Aa.start(); Bb.start(); Cc.start(); }} public class TestFiles { public static void main(String[] args) { sleepThread spOne = new sleepThread("Tom"); sleepThread spTwo = new sleepThread("Jack"); sleepThread spThree = new sleepThread("Smith"); spThree.start(); try { spThree.join(); } catch (InterruptedException e) { e.printStackTrace(); } spOne.start(); spTwo.start(); }} public class PriorityThread implements Runnable { @Override public void run() { for (int i = 0; i < 10; ++i) { System.out.println(Thread.currentThread().getName() + ":" + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }}public class TestFiles { public static void main(String[] args) { PriorityThread pt = new PriorityThread(); Thread tr = new Thread(pt, "Jack"); Thread trr = new Thread(pt, "Tom"); Thread trrr = new Thread(pt, "Smith"); tr.setPriority(10); trrr.setPriority(1); tr.start(); trr.start(); trrr.start(); }} import java.util.Date;public class ThreadStop extends Thread { @Override public void run() { System.out.println("开始执行:" + new Date()); try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("线程被终止了!"); } System.out.println("结束执行:" + new Date()); }}public class ThreadStopDemo { public static void main(String[] args) { ThreadStop ts = new ThreadStop(); ts.start(); try { Thread.sleep(3000); ts.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } }} 线程组允许管理多个线程,线程池提供高效的线程执行服务。
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ExecutorsDemo { public static void main(String[] args) { ExecutorService pool = Executors.newFixedThreadPool(2); pool.submit(new MyRunnable()); pool.submit(new MyRunnable()); pool.shutdown(); }} import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Future;class MyCallable implements Callable { private int number; public MyCallable(int number) { this.number = number; } @Override public Integer call() throws Exception { int sum = 0; for (int x = 1; x <= number; x++) { sum += x; } return sum; }}public class CallableDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService pool = Executors.newFixedThreadPool(2); Future result_01 = pool.submit(new MyCallable(50)); Future result_02 = pool.submit(new MyCallable(100)); Integer sumOne = result_01.get(); Integer sumTwo = result_02.get(); System.out.println("Sum<50>: " + sumOne); System.out.println("Sum<100>: " + sumTwo); pool.shutdown(); }} public class ThreadInner { public static void main(String[] args) { new Thread() { public void run() { for (int x = 0; x < 100; x++) { System.out.println(Thread.currentThread().getName() + ":" + x); } } }.start(); new Thread(new Runnable() { @Override public void run() { for (int x = 0; x < 100; x++) { System.out.println("hello:" + x); } } }) { public void run() { for (int x = 0; x < 100; x++) { System.out.println("world:" + x); } } }.start(); }} import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask;class DeleteFolder extends TimerTask { @Override public void run() { File srcFolder = new File("其他文件"); deleteFolder(srcFolder); } private void deleteFolder(File srcFolder) { File[] fileArray = srcFolder.listFiles(); if (fileArray != null) { for (File file : fileArray) { if (file.isDirectory()) { deleteFolder(file); } else { System.out.println(file.getName() + ":" + file.delete()); } } System.out.println(srcFolder.getName() + ":" + srcFolder.delete()); } }}public class TimerTest { public static void main(String[] args) throws ParseException { Timer t = new Timer(); String s = "10:05 2018/11/11"; SimpleDateFormat sdf = new SimpleDateFormat("HH:mm yyyy/MM/dd"); Date d = sdf.parse(s); t.schedule(new DeleteFolder(), d); }} 转载地址:http://aewiz.baihongyu.com/