多线程学习笔记1

xiaoxiao2021-02-27  464

一直想写多线程爬虫,但是对多线程编程不太熟悉,买了两本书<<多线程编程核心技术>>,<<java并发编程实战>>,边看边学边做笔记

多线程编程1: 两种方法实现 1:继承Thread类 class Thread1 extends Thread{ public void run(){ syso("Thread1") } public static void main(String[] args){ new Thread1().start } } 2:实现Runnable接口 class Thread1 implements Runnable{ public void run(){ syso("Thread1") } public static void main(String[] args){ new Thread(new Thread1).start() } } 在主函数中执行start()方法的顺序不代表线程的启动顺序,这里涉及到一个线程安全问题 在单线程环境中,如果向某个变量先写入值,在没有其他写入操作的情况下读取这个变量,那么总能得到相同的值 然而,在读和写操作在不同的线程中执行时,情况并非如此,例如: public class Novisibility { private static boolean ready; private static int number; private static class ReaderThread extends Thread{ public void run(){ while(!ready) Thread.yield(); System.out.println(number); } } public static void main(String[] args){ new ReaderThread().start(); number = 45; ready = true; } } Novisibility可能会持续循环下去,因为线程可能永远都看不到ready的值,也可以能会输出0,因为读线程读到了写入ready 的值,但是没有看到之后写入的number值,这种现象称为重排序(虽然我运行了一下,每次都能正常输出......) 线程不安全问题造成的原因有许多种,比如多个线程共享一个变量,如以下代码 public class Test1{ private ExpensiveObject instance = null; public ExpensiveObject getInstance(){ if(instance == null){ instance = new ExpensiveObject(); return instance; } } } 若有两个线程a和b同时执行getInstance,a看到instance为空,即将初始化一个类,此时b抢到执行权,同样判断instance为空, 初始化一个类,此时a抢到执行权,又会初始化一次instace,出现线程安全问题 可以通过同步代码块来支持原子性使上述方法变为线程安全的方法 public class Test1{ private ExpensiveObject instance = null; public synchronized ExpensiveObject getInstance(){ if(instance == null){ instance = new ExpensiveObject(); return instance; } } } synchronized保证了每次只能有一个线程执行该关键字保护的代码块,相当于一种互斥体,但是会造成性能降低 线程的停止: 大多数停止一个线程的操作使用Thread.interrupt()方法,但是interrupt()方法的效果并不是马上停止循环,而是仅仅相当于在当 前线程中打了一个停止的标记,例如以下代码 public class MyThread extends Thread{ public void run(){ super.run(); for(int i = 0;i < 50000;i++){ System.out.println("i="+i); } } public static void main(String[] args){ MyThread thread = new MyThread(); thread.start(); thread.interrupt(); } } 虽然调用了interrupt()方法,但是线程没有停止 判断线程是否停止状态 1:this.interrupted(),用于测试当前线程是否已经中断 静态方法,当前线程指的是运行this.interrupted()方法的线程,线程的中断状态会被该方法清除,如以下代码: MyThread thread = new MyThread(); thread.start(); Thread.sleep(1000); Thread.currentThread().interrupt(); System.out.println("是否停止1?="+thread.interrupted()); System.out.println("是否停止2?="+thread.interrupted()); 控制台会打印一个true一个false 2:this.isInterrupted(),测试线程是否已经中断 非静态方法,测试线程Thread对象是否已经是中断状态,但不清除状态 由此可以在线程中使用for语句来判断线程是否是停止状态,如果是停止状态,让后面的代码不运行 public class MyThread extends Thread { public void run(){ super.run(); for(int i = 0;i < 50000;i++){ if(this.interrupted()){ System.out.println("线程停止.退出"); break; } System.out.println("i="+i); } System.out.println("end"); } public static void main(String[] args) throws InterruptedException{ MyThread thread = new MyThread(); thread.start(); Thread.sleep(20); thread.interrupt(); } } 实际上线程并未停止,只是for循环终止,可以通过抛出异常来直接停止线程 public class MyThread extends Thread { public void run(){ super.run(); try { for(int i = 0;i < 50000;i++){ if(this.interrupted()){ throw new InterruptedException(); } System.out.println("i="+i); } System.out.println("end"); }catch(InterruptedException e){ System.out.println("线程已退出"); } } public static void main(String[] args) throws InterruptedException{ MyThread thread = new MyThread(); thread.start(); Thread.sleep(20); thread.interrupt(); } } 线程的暂停: 1.suspend()和resume()方法(已作废) public class MyThread extends Thread { private long i = 0; public long geti(){ return i; } public void seti(long i){ this.i = i; } public void run(){ while(true){ i++; } } public static void main(String[] args){ try{ MyThread thread = new MyThread(); thread.start(); Thread.sleep(5000); //第一段 thread.suspend(); System.out.println("第一段="+System.currentTimeMillis()+"i="+thread.geti()); Thread.sleep(5000); System.out.println("第一段="+System.currentTimeMillis()+"i="+thread.geti()); //第二段 thread.resume(); Thread.sleep(5000); //第三段 thread.suspend(); System.out.println("第二段="+System.currentTimeMillis()+"i="+thread.geti()); Thread.sleep(5000); System.out.println("第二段="+System.currentTimeMillis()+"i="+thread.geti()); }catch(InterruptedException e){ e.printStackTrace(); } } } 缺点 使用不当,会造成公共的同步对象的独占,使得其他线程无法访问公共同步对象 2.yield方法 放弃当前的cpu资源,让给其他任务,但放弃时间不确定, Thread.yield() 线程的优先级 线程优先级决定了谁得到的cpu资源较多,也就是cpu优先执行优先级较高的线程对象中的任务 方法:setPriority(int priorrity) 读取错误 如下程序不是线程安全的 public class Mutable { private int value; public void setvalue(int value){ this.value = value; } public int getvalue(){ return value; } } 原因是如果某个线程调用了setvalue,那么另一个正在调用getvalue的线程可能会看到更新后的value值,也可能看不到,应该进行同步 public class Mutable { private int value; public synchronized void setvalue(int value){ this.value = value; } public synchronized int getvalue(){ return value; } } 重入: 当某个线程请求一个由其他线程持有的锁时,发出请求的线程就会阻塞,然而由于内置锁的可重入,如果某个线程师徒获德 一个已经由它持有的锁,那么这个请求就会成功,重入意味着获取锁的操作粒度是线程而非调用,入下面程序 public class Test1{ public synchronized void dosomething(){ } } class Test2 extends Test1{ public synchronized void dosomething(){ super.dosomething(); } } 子类改写了父类的代码,然后调用父类的方法,此时如果如果没有可重入的锁,会产生死锁的问题,原因是Test1和Test2的 dosomething方法都是synchronized的,每个dosomething方法被调用时都会获取Test1上的锁,然而如果锁时不可以重入的,那么在 调用super.dosomething将无法获得Test1上的锁,因为该锁已经被持有,线程将永远停顿 当一个线程执行的代码出现异常时,锁自动释放 同步不具有继承性 synchronized同步代码块 用Synchronized修饰方法时,如果一个线程需要执行的时间过长,会造成等待时间过长 可以使用同步代码块解决弊端,如下 public class Task { private String getData1; private String getData2; public void doLongTimeTask(){ try{ System.out.println("task begin"); Thread.sleep(3000); String privateGetData1 = "长时间处理任务后远程返回的值1 threadname="+Thread.currentThread().getName(); String privateGetData2 = "长时间处理任务后远程返回的值1 threadname="+Thread.currentThread().getName(); synchronized(this){ getData1 = privateGetData1; getData2 = privateGetData2; } System.out.println(getData1); System.out.println(getData2); System.out.println("task end"); }catch(InterruptedException e){ e.printStackTrace(); } } } 仅仅同步有可能造成线程不安全的部分 如果一个类中有很多sunchronized方法,可以使用非this对象的锁,这样不会造成阻塞,但是必须保证多个线程持有同一个对象的锁 静态同步synchronized方法需要用.class对象的锁 在使用String作为锁时要注意常量池缓存的问题 synchronized同步方法的无限等待问题 public class Test1 implements Runnable{ public synchronized void run(){ while(true){ System.out.println(Thread.currentThread().getName()+"在运行"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args){ Test1 test = new Test1(); Thread task1 = new Thread(test); Thread task2 = new Thread(test); task1.start(); task2.start(); } } 如上代码,一个线程进入到同步方法中,进入while循环,将会一直持有锁,别的方法无法进入,使用同步代码块的方式 public class Test1 implements Runnable{ public synchronized void run(){ while(true){ synchronized(this){ System.out.println(Thread.currentThread().getName()+"在运行"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static void main(String[] args){ Test1 test = new Test1(); Thread task1 = new Thread(test); Thread task2 = new Thread(test); task1.start(); task2.start(); } } 多线程的死锁问题 不同线程都在等待不可能被释放的锁,导致所有任务都无法继续完成,如下列代码 public class DealThread implements Runnable{ public String username; public Object lock1 = new Object(); public Object lock2 = new Object(); public void setflag(String username){ this.username = username; } @Override public void run() { // TODO Auto-generated method stub if(username.equals("a")){ synchronized(lock1){ try{ System.out.println("username = "+username); Thread.sleep(3000); }catch(InterruptedException e){ e.printStackTrace(); } synchronized(lock2){ System.out.println("lock1-lock2"); } } } if(username.equals("b")){ synchronized(lock2){ try{ System.out.println("username = "+username); Thread.sleep(3000); }catch(InterruptedException e){ e.printStackTrace(); } synchronized(lock1){ System.out.println("lock1-lock2"); } } } } public static void main(String[] args){ try{ DealThread t1 = new DealThread(); t1.setflag("a"); Thread thread1 = new Thread(t1); thread1.start(); Thread.sleep(1000); t1.setflag("b"); Thread thread2 = new Thread(t1); thread2.start(); }catch(InterruptedException e){ e.printStackTrace(); } } } 产生死锁的原因是程序设计的Bug,如上述程序 线程1满足第一个分支username=a,进入同步代码块获取lock1打印username,cpu资源被线程2获得 线程2满足第二个分支username=b,进入同步代码块获得lock2打印username,cpu资源被线程1获得 线程1继续执行发现lock2已经被线程2持有,进入等待,线程2获得执行权 线程2继续执行发现lock1已经被线程1持有,进入等待 死锁产生 死锁的避免 设计程序时尽量避免双方互相持有对方锁的情况

转载请注明原文地址: https://www.6miu.com/read-540.html

最新回复(0)