1.进程:
正在运行的程序称之为进程,进程是系统分配资源的基本单位。
2.线程:
(1)定义:
线程又称为轻量级进程(light weight process)。线程是进程中的一条执行路径,也是CPU的基本调度单位。若一个程序可同一时间执行多个线程,就是支持多线程的。一个进程由一个或者多个线程组成,且彼此之前可以同时执行不同的任务,成为多线程。
(2)使用多线程的意义:
充分利用CPU,提高程序的效率。
(3)java如何创建多线程:
①继承thread类:
public class MyThread extends Thread { @Override public void run(){ for (int i = 0; i <20 ; i++) { System.out.println(Thread.currentThread().getName()+"~~~~~~~~~"+i); } } }
案例:
实现四个窗口各卖100张票
public class SellTicket extends Thread { private int tick=100; @Override public void run() { while (true){ if(tick>0){ tick--; System.out.println(Thread.currentThread().getName()+"卖了一张票,剩余:"+tick+"张"); }else{ System.out.println(Thread.currentThread().getName()+"卖完了"); break; } } } }
测试:
public class Test { public static void main(String[] args) { SellTicket task=new SellTicket(); Thread t1=new Thread(task,"窗口A"); Thread t2=new Thread(task,"窗口B"); Thread t3=new Thread(task,"窗口C"); Thread t4=new Thread(task,"窗口D"); t1.start(); t2.start(); t3.start(); t4.start(); } }
②实现runnable接口:
public class MyRunnable implements Runnable{ @Override public void run() { for (int i = 0; i <20 ; i++) { System.out.println(Thread.currentThread().getName()+"~~~~~~~~~~"+i); } } }
案例:
实现四个窗口共买100张票
public class SellTicket implements Runnable { private int tick = 100; @Override public void run() { while (true) { if (tick > 0) { tick--; System.out.println(Thread.currentThread().getName() + "卖了一张票;剩余:" + tick + "张"); } else { break; } } } }
测试:
public class TestTick { public static void main(String[] args) { SellTicket task=new SellTicket(); Thread t1=new Thread(task,"窗口A"); Thread t2=new Thread(task,"窗口B"); Thread t3=new Thread(task,"窗口C"); Thread t4=new Thread(task,"窗口D"); t1.start(); t2.start(); t3.start(); t4.start(); } } //但是会出现重卖以及超卖现象,是因为多个线程共享一个资源,导致线程安全隐患问题
③实现callable接口:
public class MyCallable implements Callable<Double> { //call表示线程的任务代码. @Override public Double call() throws Exception { double sum=0; for (int i = 0; i <=100 ; i++) { sum+=i; } return sum; } }
案例:
1~1000之间求3倍数的和
public class MyCallAble implements Callable<Double> { @Override public Double call() throws Exception { Double value = 0.0; for (int i = 0; i <1000 ; i++) { if (i%3==0){ value+=i; } } return value; } }
测试:
public class Test01 { public static void main(String[] args) { MyCallAble mc = new MyCallAble(); FutureTask ft = new FutureTask<>(mc); Thread t = new Thread(ft); t.start(); try { Object o = ft.get(); System.out.println(o); } catch (Exception e) { e.printStackTrace(); } } }