------- android培训、java培训、期待与您交流! ----------
多线程
一,线程的2种创建方式
创建线程的第一种方式:继承Thread ,由子类复写run方法。
步骤:
1,定义类继承Thread类;
2,目的是复写run方法,将要让线程运行的代码都存储到run方法中;
3,通过创建Thread类的子类对象,创建线程对象;
4,调用线程的start方法,开启线程,并执行run方法。 线程状态:
新建:start()
运行:具备执行资格,同时具备执行权;
冻结:sleep(time),wait()—notify()唤醒;线程释放了执行权,同时释放执行资格; 临时阻塞状态:线程具备cpu的执行资格,没有cpu的执行权; 消亡:stop()
创建线程的第二种方式:实现一个接口Runnable。
步骤:
1,定义类实现Runnable接口。
2,覆盖接口中的run方法(用于封装线程要运行的代码)。
3,通过Thread类创建线程对象;
4,将实现了Runnable接口的子类对象作为实际参数传递给Thread类中的构造函数。 为什么要传递呢?因为要让线程对象明确要运行的run方法所属的对象。
5,调用Thread对象的start方法。开启线程,并运行Runnable接口子类中的run方法。
练习程序:
synchronized同步的使用
public void sync(){
//同步锁的对象为this.
synchronized (this) {
//需要同步的内容
}
}
public synchronized void sync(){
//同步方法
}
关于多线程的死锁
产生死锁的原因:当两个线程(使用synchornized关键字时)持有不同的锁,又同时需要访问对方的锁时,
双方互不交换锁,就可能导致产生线程的死锁
synchronized (this) {
synchronized (this) {
//同步嵌套
}
}
安全的解决方式
解决安全问题
*/
class Res
{
String name;
String sex;
}
class Input implements Runnable
{
private Res r;
//Object obj=new Object();
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(Safe.class)
{
if(x==0)
{
r.name="mack";
r.sex="man";
}
else
{
r.name="小丽";
r.sex="女女";
}
x=(x+1)%2;
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(Safe.class)
{
System.out.println(r.name+"。。。。"+r.sex);
}
}
}
}
class Safe
{
public static void main(String[] args)
{
Res r=new Res();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}