java线程基础
来源:互联网 发布:linux双系统引导修复 编辑:程序博客网 时间:2024/06/09 17:42
线程的开启
- 继承Thread类,重写run()方法
- 数据不共享
class MyThread extends Thread { private int ticket = 5; @Override public void run() { }}public class MyLearn { public static void main(String[] args) throws Exception { MyThread mt1 = new MyThread(); mt1.start(); MyThread mt2 = new MyThread(); mt2.start(); //两线程分别5个ticket }}
- 实现Runnable接口,实现run()方法
- 静态代理模式:
- Thread和MyThread都实现Runnable接口
- Thread作为代理,包含MyThread的引用
- 严格的代理设计模式之中应该是调用Thread.run(),而此处调用start()
- 方便表示数据共享的概念
- 静态代理模式:
public class MyLearn { public static void main(String[] args) throws Exception { MyThread mt1 = new MyThread(); new Thread(mt1).start(); MyThread mt2 = new MyThread(); new Thread(mt2).start(); //两线程共享ticket }}class MyThread implements Runnable { private int ticket = 5; @Override public void run() { }}
- 实现Callable接口,重写call()方法
- 优点:call()方法可以抛异常并且可以带返回值,run()不可以
class MyThread implements Callable<String> { @Override public String call() throws Exception { Thread.sleep(2000); return "hello"; }}public class MyLearn { public static void main(String[] args) throws Exception { ExecutorService threadpool=Executors.newFixedThreadPool(1); Future<String> future = threadpool.submit(new MyThread()); String s = future.get(); //主线程被阻塞,直到call()方法返回 System.out.println(s); threadpool.shutdown(); }}
线程的停止
- stop() suspend()方法 已过时
- 标志位
- volatile关键字:解决线程私有堆栈中数据和公共堆栈中的数据不同步
- volatile关键字:解决线程私有堆栈中数据和公共堆栈中的数据不同步
public class MyLearn { public static void main(String[] args) throws Exception { MyThread mt1 = new MyThread(); Thread thread = new Thread(mt1); thread.start(); Thread.sleep(2000);//验证不加volatile时,不输出run end mt1.stop(); }}class MyThread implements Runnable { private int ticket = 5; private volatile boolean flag=true; //volatile解决线程的可见性,并不能保证原子性 public void stop(){ flag=false; } @Override public void run() { while(flag){ } System.out.println("run end"); }}
- 中断线程
- 当线程处于阻塞态,标志位方法不好用,可以interrup()打破阻塞
- public static boolean interrupted() 测试当前线程是否中断并清除中断状态
- public boolean isInterrupted() 测试线程是否中断,不影响线程的状态;
public class MyLearn { public static void main(String[] args) throws Exception { MyThread mt1 = new MyThread(); Thread thread = new Thread(mt1); thread.start(); int num = 0; while (true) { Thread.sleep(500); num++; if ( num== 3) { mt1.setFlag(false); thread.interrupt(); break; } } }}class MyThread implements Runnable { private int ticket = 5; private volatile boolean flag = true; public void setFlag(boolean f){ this.flag=f;} @Override public void run() { while (flag) { try { Thread.sleep(3500); } catch (InterruptedException e) { System.out.println("over"); //e.printStackTrace(); } } }}
class MyThread implements Runnable { private int ticket = 5; @Override public void run() { for(int j=0;j<500000;j++){ System.out.println("j="+j); if(Thread.currentThread().interrupted()){ try { throw new InterruptedException("thread is interrupted"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); break; } } } }}
线程的阻塞
- public static void sleep(long millis) throws InterruptedException
- 阻塞当前线程,不释放锁,睡醒后进入就绪状态
- 捕获InterruptedException
- public static void yield()
- 当前线程进入就绪态,不抛出异常
- 把机会让给相同或者更高优先级的线程,重新争夺
- public void join()
- 在当前线程中调用另一个线程的join()方法,当前线程转入阻塞状态,直到另一个线程结束,当前线程再由阻塞转为就绪状态。
- public void wait()
- 属于Object类的方法,在同步方法或同步块中使用,释放锁
- 使当前拥有对象锁的线程等待,直到其他线程调用notify()
- synchronized
- 多线程访问同一份资源,保证线程安全,同步粒度太小易造成死锁
- 同步方法; 同步代码块 (引用类型,this,类.class)
线程的状态
线程的信息
- public Thread(Runnable target, String name);
- public final void setName(String name);
- public final String getName();
- public static Thread currentThread()
- public final void setPriority(int newPriority);
- public final int getPriority();
- public final boolean isAlive ();
- public final boolean isDaemon(): //是否是守护线程
- public void setDaemon(boolean on) //在start()方法调用前设置
线程的同步
- synchronized
- 当一个线程访问object的一个synchronized时,另一个线程仍然可以访问该object中的非synchronized
- synchronized关键字不能继承
- 生产者消费者模式解决死锁:wait()/notify()
public class MyLearn { public static void main(String[] args) throws Exception { burgerStack bs=new burgerStack(); producer p=new producer(bs); consumer c=new consumer(bs); Thread tp=new Thread(p); Thread tc=new Thread(c); tp.start(); tc.start(); }}class producer implements Runnable { burgerStack bs=null; public producer(burgerStack bs) { super(); this.bs = bs; } @Override public void run() { for(int i=0;i<20;i++){ burger b=new burger(i); bs.push(b); System.out.println("produce"+b.id); } }}class consumer implements Runnable{ burgerStack bs=null; public consumer(burgerStack bs) { super(); this.bs = bs; } @Override public void run() { for(int i=0;i<20;i++){ burger b=bs.pop(); System.out.println("consume"+b.id); } }}class burger { int id; public burger(int id) { this.id = id; }}class burgerStack { burger[] burgerArr = new burger[6]; int index = 0; public synchronized void push(burger in) { while(index==burgerArr.length){ //用while而非if防中断跳出if try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); burgerArr[index] = in; index++; } public synchronized burger pop() { while(index==0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index--; return burgerArr[index]; }}
阅读全文
0 0
- 线程之一:JAVA线程基础
- 线程之一:JAVA线程基础
- java线程学习基础
- Java基础 -- 线程
- Java基础 -- 线程2
- JAVA线程基础
- Java 线程基础
- Java线程基础1
- java线程基础
- java基础 线程
- Java 线程基础
- java 线程基础
- 十三、Java线程基础
- java线程基础
- java基础之线程
- JAVA线程基础(一)
- Java基础之线程
- java基础--线程总结
- 基于VUE评论组件的组件自闭声明周期思考
- 50.Scala中Variance变化点及其在Spark中的应用源码解析
- selenium和webdriver区别
- 学习计划
- 实训一的学习计划
- java线程基础
- 第三周第二课
- Spring Boot-V1.5.7关闭Banner
- linux、unix下设置oracle环境变量
- Photon_对NHibernate增删改查的封装_008
- 9.23日常总结
- hdu 6158 The Designer && 计蒜客 Finding the Radius for an Inserted Circle 笛卡尔定理应用+韦达定理
- 文件夹加密
- SpringBoot配置Https