- 多线程基础方法
-
class runableDemo implements Runnable{ private String name; private int i; public runableDemo(){} public runableDemo(String name,int i) { this.name=name; this.i=i; } @Override public void run() { for (i = 0; i < 10; i++) { System.out.println(name + "运行 : " + i); } } public static void main(String[] args) { System.out.println("主线程运行开始!"); int i = 0; runableDemo runableDemo1 = new runableDemo("D",i); runableDemo runableDemo2 = new runableDemo("hhh",i); runableDemo runableDemo3 = new runableDemo("123",i); Thread thread1 = new Thread(runableDemo1); Thread thread2 = new Thread(runableDemo2); Thread thread3 =new Thread(runableDemo3); thread1.start(); thread2.start(); thread3.start(); thread3.interrupt(); /* try { thread1.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }*/ try { thread1.join(); thread2.join(); thread3.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("主线程运行结束!"); } }
- setPriority()方法是设置线程的优先级。
- join()方法是让所有子线程都执行完毕,才会执行主线程。
- yield()是让当前线程进入到可执行的状态,该线程就会把CPU时间让掉,让其他或者自己的线程执行(也就是谁先抢到谁执行)
- Sleep()是使当前线程睡眠几秒,进入不可运行状态
- interrupt():不是中断某个线程,它只是线程发送一个中断信号,让线程在无限等待时(如死锁时)能抛出,从而结束线程,但是如果你吃掉了这个异常,那么这个线程还是不会中断的。
- isAlive(): 判断一个线程是否存活。
- 运行结果:
-
- 通過一个经典问题:建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC。说明wait和notify方法
-
class runableDemo implements Runnable{ private String name; private Object prev; private Object self; private runableDemo(String name, Object prev, Object self) { this.name = name; this.prev = prev; this.self = self; } @Override public void run() { int count = 5; while (count > 0) { synchronized (prev) { synchronized (self) { System.out.println(Thread.currentThread().getName()); System.out.println(name); count--; self.notify(); } try { prev.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) throws Exception { Object a = new Object(); Object b = new Object(); Object c = new Object(); runableDemo A = new runableDemo("A", c, a); runableDemo B = new runableDemo("B", a, b); runableDemo C = new runableDemo("C", b, c); new Thread(A).start(); Thread.sleep(50); //确保按顺序A、B、C执行 new Thread(B).start(); Thread.sleep(50); new Thread(C).start(); Thread.sleep(50); } }
- 运行结果:
-
- wait(): 强迫一个线程等待。
- notify(): 通知一个线程继续运行。
- 注:wait就是说线程在获取对象锁后,主动释放对象锁,同时本线程休眠;sleep使线程睡眠但是不释放对象锁。wait()和sleep()都可以通过interrupt()方法 打断线程的暂停状态 ,从而使线程立刻抛出InterruptedException
多线程基础方法小结
最新推荐文章于 2019-09-08 18:01:44 发布