线程练习题
1:
1.画图说明线程的生命周期,以及各状态切换使用到的方法等
状态,方法
2:
2.同步代码块中涉及到同步监视器和共享数据,谈谈你对同步监视器和共享数据的理解,以及注意点。
同步监视器: 可以是任意一个对象来操作也就是锁, 多个线程使用的都必须是同一个监视器 共享数据: 多个线程共同操作的数据 一个线程操作此数据 另一个都不能用了 synchronized{ 操作共享数据的代码}
3 sleep()和wait()的区别
sleep() 让线程停止的时间 我们制定一个时间到了时间自动结束
wait() 是让线程阻塞, 需要被notify() 或者notifyAll()唤醒
使用不同sleep()是在Thread类中
wait()是在Object类中
4:写一个线程安全的懒汉式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class lanhanTT { private lanhanTT(){}; private static lanhanTT lanhanTT = null; public static synchronized lanhanTT show (){ if(lanhanTT == null){ lanhanTT = new lanhanTT(); } return lanhanTT; } } class lanhan{ public static void main(String[] args) { lanhanTT l1 = lanhanTT.show(); lanhanTT l2 = lanhanTT.show(); System.out.println(l1); System.out.println(l2); } }
5 创建多线程有哪几种方式:4种
继承Thread 类
实现Runnable 接口
实现Callable接口
线程池 ExecutorService
6: 同步机制有哪几种
1: 同步代码块 synchronized(锁){共享代码} 2: 同步方法 3: local
7: 用线程通信写出1-100的多线程操作
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class InterviewOne { public static void main(String[] args) { InterviewTestOne t1 = new InterviewTestOne(); Thread thread1 = new Thread(t1); Thread thread2 = new Thread(t1); thread1.setName("a"); thread2.setName("b"); thread1.start(); thread2.start(); } } class InterviewTestOne implements Runnable { boolean flag = false; private int num = 1; @Override public void run() { add(Thread.currentThread().getName()); } private synchronized void add(String name) { if (name.equals("a")) { while (num <= 100) { if (flag == false) { System.out.println(Thread.currentThread().getName() + " : " + num); num++; flag = true; notify(); } else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } else if (name.equals("b")) { while (num <= 100) { if (flag == true) { System.out.println(Thread.currentThread().getName() + " : " + num); num++; flag = false; notify(); } else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }