第六章 多线程
必须掌握知识点
单线程就是run执行完之后才能执行别的进程
多进程情况下就是main方法调用子线程的方法 调用thread类中的start方法启动线程并运行线程中的run方法
new thread()对象表示创建一个线程 如果调用new thread().start()表示启动一个线程 则会启动start中的run方法
如果run为空 则在线程方法中必须重新run方法 才能使线程运行
通过子类创建线程对象
Class testthread extends thread 中 new testthread().start()可以实现多态性
Run方法结束表示线程结束 如果用setdaemon(true)表示线程变成了后台线程 如果没有 就是前台线程
只用有一个前台线程进行 则线程就不会停止
只用后台线程进行时 线程就会停止
联合线程join()是将一个线程联合到另外一个线程
在线程中经常使用runnable 其调用的是runnable中的方法而不是run中的方法
线程只有一个对象 用对象启动多个线程 这种情况下 只有一个线程运行
使用runnable可以实现资源共享 可以避免单线程的局限
多个线程可以使用同一个对象 实现资源共享
创建一个资源对象 和多个线程 多个线程接受runnable对象参数作为对象 可以实现资源同步
线程死锁
A线程等待B线程监视器的对象 而B线程等待A线程监视器的对象 当AB线程都等不到监视器对象的时候 就进入了死锁状态
多线程同步 不要抱着侥幸的心理 要把各种情况考虑清楚 不然会使程序陷入软件危机
同步代码块和同步方法 使用synchronized修饰 同步方法所使用的对象是this对象 只用使用同一个资源对象的才能实现资源同步。
线程间的通信 wait ()等待 notify()唤醒 notifyall 唤醒所有等待的线程
线程对象A作为同步监视器对象 则等待 唤醒方法都必须使用A才可以实现资源同步
如A.wait()等
线程通信例子
class Producer implements Runnable
{ Q q;
public void Producer(Q q)
{this.q=q;
}
public void run()
{ int i=0;
while(true)
{
synchronized(q)
{if (q.bFull)
wait();
if (i==0)
{q.name="zhangshan";
try{Thread.sleep(1);}catch(Exception e){}
q.sex="male";
}
else
{q.name="lisi";
q.sex="female";
}
q.bFull=true;
notify();
}
i=(i+1)%2;
}
}
}
class Comsumer implements Runnable
{ Q q;
public void Consumer(Q q)
{this.q=q;
}
public void run()
{
while(true)
{ synchronized(q)
{ if (!q.bFull)
wait();
System.out.println(q.name);
System.out.println(":"+q.sex);
q.bFull=false;
notify();
}
}
}
}
class Q
{ String name="unknown";
String sex="unknown";
boolean bFull=false;
}
class Threadconmunication
{
public static void main(String[] args)
{
Q q=new Q();
new Thread(new Producer(q).start());
new Thread(new Consumer(q).start());
}
}