(JAVA)线程
线程的创建
方式一:Thread
public class dome {public static void main(String[] args) {MyThread myThread = new MyThread();myThread.start();for(int i=1;i<=5;i++){System.out.println("主线程"+i);}}
}
public class MyThread extends Thread{@Overridepublic void run() {for(int i=0;i<5;i++){System.out.println("MyThread线程"+i);}}
}
方式二:Runnable
public class dome {public static void main(String[] args) {Runnable r = new MyRunnable();new Thread(r).start();for(int i=1;i<=5;i++){System.out.println("主线程"+i);}}
}
public class MyRunnable implements Runnable{@Overridepublic void run() {for(int i=1;i<=5;i++){System.out.println("MyRunnable"+i);}}
}
方式三:Callable
public class dome {public static void main(String[] args) throws ExecutionException, InterruptedException {//3.创建一个Callable对象Callable c = new MaCallable(100);//4.把Callable对象封装成一个FutureTask对象(任务对象)FutureTask<String> f = new FutureTask<>(c);//作用//1.是一个任务对象,实现了Ruuable类//2.可以用get()方法获取任务执行完后的结果new Thread(f).start();//获取执行完之后的结果//如果此时还未执行完,则在此等待String s = f.get();System.out.println(s);}
}
//1.实现Callable接口
public class MaCallable implements Callable<String> {private int n;public MaCallable(int n){this.n=n;}//2.重写call方法@Overridepublic String call() throws Exception {int sum=0;for(int i=1;i<=n;i++){sum+=i;}return "1-"+n+"的和为:"+sum;}
}
Thread常用方法
public class dome {public static void main(String[] args) throws ExecutionException, InterruptedException {Thread t1 = new MyThread("1号");
// t1.setName("1号");//设置线程名称t1.start();Thread t2 = new MyThread("2号");
// t1.setName("2号");t2.start();Thread t = Thread.currentThread();for(int i=1;i<=5;i++){System.out.println(t.getName()+"线程"+i);}}
}
public class MyThread extends Thread{public MyThread(String name){super(name);}@Overridepublic void run() {Thread t = Thread.currentThread();//用来获取线程名称for(int i=0;i<5;i++){System.out.println(t.getName()+"线程"+i);}}
}
public class dome {public static void main(String[] args) throws ExecutionException, InterruptedException {for(int i=1;i<=5;i++){if(i==3){//休眠5秒Thread.sleep(5000);}System.out.println(i);}//join:让当前线程先跑完Thread t1 = new MyThread("1号");t1.start();t1.join();Thread t2 = new MyThread("2号");t2.start();Thread t3 = new MyThread("3号");t3.start();t2.join();}
}
线程同步
线程安全
线程同步的几种方式
1.同步代码块 (比2好)
public void dr(int n) {String name = Thread.currentThread().getName();synchronized (this) {//实力方法建议用this,静态方法建议用。classif(n<=num){System.out.println(name+"取钱"+n);num-=n;System.out.println(name+"剩"+num);}else {System.out.println(name+"不足");}}}
2.同步方法(可读性好)
public synchronized void dr(int n) {String name = Thread.currentThread().getName();if(n<=num){System.out.println(name+"取钱"+n);num-=n;System.out.println(name+"剩"+num);}else {System.out.println(name+"不足");}}
3.Lock锁
private final Lock l = new ReentrantLock();public synchronized void dr(int n) {String name = Thread.currentThread().getName();//加锁try {l.lock();if(n<=num){System.out.println(name+"取钱"+n);num-=n;System.out.println(name+"剩"+num);}else {System.out.println(name+"不足");}} catch (Exception e) {throw new RuntimeException(e);} finally {//防止程序出错时不能解锁//解锁l.unlock();}}
线程池
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
1.corePoolSize:线程池的核心线程数量
2.maximumPoolSize:线程池的最大线程数量(多出的为临时线程)
3.keepAliveTime:临时线程的存活时间
4.unit:临时线程存活时间的单位
5.workQueue:线程池的任务队列
6.threadFactory:指定线程池的线程池的线程工厂
7.handler:线程池的拒绝策略
处理Runnable
public class dome {public static void main(String[] args) throws ExecutionException, InterruptedException {/* public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler)*/ExecutorService e = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS,new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());//LinkedBlockingQueue<>(),链表,无限大小MyThread myThread = new MyThread();e.execute(myThread);e.execute(myThread);e.execute(myThread);e.execute(myThread);e.execute(myThread);e.execute(myThread);e.execute(myThread);//添加临时线程e.execute(myThread);e.execute(myThread);//达到最大值e.execute(myThread);
// e.shutdown();//等线程执行完后,关闭线程
// e.shutdownNow();//直接关闭线程}
}
处理Callable
public class dome {public static void main(String[] args) {/* public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler)*/ExecutorService e = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS,new ArrayBlockingQueue<>(4), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());//LinkedBlockingQueue<>(),链表,无限大小Future<String> f1 = e.submit(new MaCallable(100));Future<String> f2 = e.submit(new MaCallable(200));Future<String> f3 = e.submit(new MaCallable(300));Future<String> f4 = e.submit(new MaCallable(400));try {System.out.println(f1.get());System.out.println(f2.get());System.out.println(f3.get());System.out.println(f4.get());} catch (InterruptedException ex) {System.out.println(ex.getLocalizedMessage());} catch (ExecutionException ex) {System.out.println(ex.getLocalizedMessage());}}
}