1、程序死锁
过多的同步有可能出现死锁,死锁的操作一般在程序运行的时候才有可能出现。
多线程要进行资源的共享,就需要同步,但同步过多,就可能造成死锁。
程序中出现死锁的一般原因就是在当前的同步方法中调用了其它对象的同步方法, 在我们编程时要注意避免这样写 。死锁的发生的是不确定性的!
下面用一个程序演示,但不一定会这样写。
package com.xiaofeng.example;
/**
* 死锁
* @author XiaoFeng1015
*/
public class ThreadDemo3 {
public static void main(String[] args) {
new DeadThread();
}
}
// 顾客类
class Customer{
public synchronized void say(Waiter w){
System.out.println("顾客说:先吃饭在买单!");
w.doService();
}
public synchronized void doService(){
System.out.println("同意了,买完单再吃饭!");
}
}
// 服务员
class Waiter{
public synchronized void say(Customer c){
System.out.println("服务员说:先买单再吃饭");
c.doService();
}
public synchronized void doService(){
System.out.println("同意了,吃完饭再买单!");
}
}
class DeadThread implements Runnable {
Customer c= new Customer();
Waiter w = new Waiter();
public DeadThread(){
new Thread(this).start();
w.say(c);
}
@Override
public void run() {
c.say(w);
}
}
运行结果:
2、程序中断
停止一个线程,目前一些destroy()方法已经过时,可以使用中断的方式停止程序。
在停止一个程序时,也需要一些准备工作。
package com.xiaofeng.example;
public class TheadDemo4 {
public static void main(String[] args) throws InterruptedException {
MyThread my = new MyThread();
Thread t1 = new Thread(my);
t1.start();
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
}
// 当i=10;时,设置flag为false,中断程序执行
my.flag = false;
}
static class MyThread implements Runnable {
// 用flag做中断标记
public boolean flag;
public MyThread() {
flag = true;
}
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("i=" + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}
}
}
执行结果:
未完持续…….
期待和大家的交流,谢谢喽!!