多线程案例
public class thread2{ public static void main(String[] args) { ticket Ticket1 = new ticket(); ticket Ticket2 = new ticket(); Ticket1.start(); Ticket2.start(); } } class ticket extends Thread{ private static int num = 100;//让多个线程共享这个num,static修饰 @Override public void run(){ while(true) { if(num == 0){ break; } try { Thread.sleep(50); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(Thread.currentThread().getName()+(100-(num--))+"张票"); } } }
以上程序是有bug的.运行以后我们发现他竟然可以超过票数,一直卖下去,问题出在哪里?
下面我们使用runnable方式操作一下.结果发现在休眠时间长的情况下就不会超卖,短了就有可能.这是因为时间片轮转操作的问题(操作系统的内容)
public class thread2{ public static void main(String[] args) { ticket Ticket = new ticket(); Thread thread1 = new Thread(Ticket); Thread thread2 = new Thread(Ticket); thread1.start(); thread2.start(); } } class ticket implements Runnable{ private int num = 100;//让多个线程共享这个num,static修饰 @Override public void run(){ while(true) { if(num == 0){ break; } try { Thread.sleep(5); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(Thread.currentThread().getName()+(100-(num--))+"张票"); } } }
线程终止
在主线程中通过set方法修改loop变量,通知进程阻塞
线程常用方法
Interrupt:中断休眠,而不是终止子线程
这是子线程.我们输出吃包子100次,然后休眠20秒.catch一个中断异常,意思是如果在执行try里面的内容时出现了中断异常,就会输出对应的xxx被interrupt了
当程序执行到这里时会中断子线程的休眠
(子线程和主线程是并行的,主线程执行五秒后 会中断子线程为期20秒的休眠)
更改/查看线程优先级
setPriority()
getPriority()
线程的礼让和插队
以下代码实验成功.
CPU判断如果资源不紧张,那么调用yield不成功,如果资源紧张则会让子线程先执行.
join则是强制先执行
public class thread3 { public static void main(String[] args) throws InterruptedException { T t = new T(); t.start(); for (int i = 0; i < 20; i++) { Thread.sleep(300); System.out.println("主线程吃包子"+i); if(i==5) { System.out.println("子线程先吃--------------------------"); t.join();//这里是阻塞主线程,让子线程先执行完毕,执行完毕后继续主线程 System.out.println("继续主线程--------------------"); } } } } class T extends Thread { @Override public void run(){ for (int i = 0; i < 20; i++) { try { Thread.sleep(300); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("子线程吃了"+i+"个包子"); } } }
综合练习
public class thread3 { public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new T()); for (int i = 1; i <= 10; i++) { System.out.println("Hi" + i); Thread.sleep(400); if (i == 5) { System.out.println("T join"); t.start(); t.join(); } } } } class T implements Runnable { @Override public void run(){ for (int i = 0; i < 10; i++) { try { Thread.sleep(400); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("HELLO" + i); } } }
以上为韩顺平老师课程后本人总结的笔记