public class ThreadDemo2 { public static void main(String[] args) { // 创建Thread对象,传递Runnable接口的实现类对象 Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); Thread t3 = new Thread(t); Thread t4 = new Thread(t); t1.start(); t2.start(); t3.start(); t4.start(); } } 线程的通信: 多线程操作共享数据的方向不同;
线程的等待与唤醒机制,实现间隔输出;
wait notify 必须有同步,必须是锁调用;
等待唤醒写在Objec类中;
线程的停止方式:
利用变量,结束run方法;
利用异常结束run方法,Thread类的interrupt方法; 代码举例:
class Stop implements Runnable{ private boolean flag = true; public void run(){ while(flag){ synchronized(this){ try{ this.wait(); }catch(Exception e){ System.out.println("线程被打了"); flag = false; } System.out.println("run..."); } } } public void setFlag(boolean flag){ this.flag = flag; } } public class ThreadStopDemo { public static void main(String[] args) { Stop s = new Stop(); Thread t = new Thread(s); t.start(); for(int x = 0 ; x < 100 ; x++){ if(x == 99) //s.setFlag(false); t.interrupt(); System.out.println("main..."+x); } } }