多线程
线程间通信
多个线程处理同一资源,但是任务却不同。
class Resource//资源
{
String name;
String sex;
}
class Input implements Runnable//输入
{
Resource r ;
Input(Resource r)
{
this.r = r;
}
public void run()
{
int x = 0;
synchronized(r)//只有在输入和输出都设置同步才能保证打印的信息匹配
{
while(true)
{
if(x==0)
{
r.name =Fang ;
r.sex = m;
}
else
{
r.name = Li;
r.sex = f;
}
x = (x+1)%2;
}
}
}
}
class Output implements Runnable//输出
{
Resource r ;
Output(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
System.out.println(r.name+"..."+r.sex);
}
}
}
}
class ResourceDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
等待/唤醒机制
- wait():让线程处于冻结状态,被wait的线程会被存储到线程池中。
- notify():唤醒线程池中的一个任意线程
- notifyAll():唤醒池中的所有线程
- 这些方法都必须定义在同步中
Lock接口
Lock代替了synchronized方法和语句使用
import java.util.concurrent.locks.*;
Lock lock = new ReentrantLock();
void show()
{
try{
lock.lock();//获取锁
任务代码...throw Exception();
}
finally{
lock.unlock();//释放锁
}
}//将锁和同步都封装成了对象
接口Condition
Condition替代了Object监视器方法(wait,notify,notifyAll)的使用
- 以前:Object对象一把锁只有一组监视器方法(wait+notify,或者wait+notifyAll)
- 现在:多个Condition对象可以对应一个锁,每个condition都有一组监视器
- 好处:能随时和锁进行绑定,如下图所示
- 包含的方法为:await();signal();signalAll();
线程停止
可以使用interrupt()方法将线程从冻结状态强制恢复到运行状态,让线程具备CPU执行资格,但是强制动作会发生InterruptedException,需要处理。
守护线程
t1.setDaemon();
守护线程运行时同其他线程一样,但不需要手动结束,只要其他线程结束,守护线程自动消失。
-
t1.join():执行此代码的线程会等待该线程终止才去争夺执行权,当临时加入一个线程运算时可以使用join
-
t1.setPriority(Thread.MAX_PRIORITY):将线程的优先级设为最大值10,默认为5,最小为1
class ThreadTest
{
public static void main(String[] args)
{
new Thread()
{
public void run()
{
for(int x=0; x<50; x++)
{
System.out.println("x="+x);
}
}
}.start();
for(int x=0; x<50; x++)
{
System.out.println("y="+x);
}
Runnable r = new Runnable()
{
public void run()
{
for(int x=0; x<50; x++)
{
System.out.println("z="+x);
}
}
};
new Thread(r).start();
}
}
class ThreadTest
{
public static void main(String[] args)
{
new Thread (new Runnable()
{//new Thread()线程对象{线程的子类对象}
public void run()
{
System.out.println("runnable run");
}
})
{
public void run()
{
System.out.println("subThread run");
}
}.start();//线程对象调用start()
}
}//输出结果为:subThread run(以子类的任务为主)