有这么一道题:
有个 i 默认为0,执行结果为:
线程1 : i =0
线程2 : i =1
线程1 : i =2
线程2 : i =3
线程1 : i =4
线程2 : i =5
线程1 : i =6
线程2 : i =7
线程1 : i = 8
线程2 : i = 9
线程1 : i =10
有个 i 默认为0,执行结果为:
线程1 : i =0
线程2 : i =1
线程1 : i =2
线程2 : i =3
线程1 : i =4
线程2 : i =5
线程1 : i =6
线程2 : i =7
线程1 : i = 8
线程2 : i = 9
线程1 : i =10
编写代码?
以下是只通过 同步处理的实现,还没有进行线程间通信。这是个解决办法,但是这里最重要的是静态的使用。
而Handler 通信机制里,其实非常重要的一点是 ThreadLocal是静态的,所有可以实现线程间的通信
/**
* Created by malei on 2017/10/25.
*/
public class Test {
private static int i = 0;
private static Object obj1 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Test().new myRunn1(), "狗先");
t1.start();
Thread t2 = new Thread(new Test().new myRunn2(), "猫先");
t2.start();
}
class myRunn1 implements Runnable {
public void run() {
while (true) {
synchronized (obj1) {
if (i < 10) {
if (i % 2 == 0) {
i++;
log(i);
}
} else {
return;
}
}
}
}
}
class myRunn2 implements Runnable {
public void run() {
while (true) {
synchronized (obj1) {
if (i < 10) {
if (i % 2 == 1) {
i++;
log(i);
}
} else {
return;
}
}
}
}
}
public static void log(int con) {
System.out.println(Thread.currentThread().getName() + ":" + con);
}
}
第二种方式是通过wait/notify的方式进行线程通信处理,这里有个标志位是重点! 其实在写这个代码的时候,我发现notify/wait的释放锁的时机,其实才是重点,notify只是唤醒一个等待资源的线程,但是并不会让等待的线程马上执行。而是要等待该线程执行完,或者执行wait后,才真正的释放资源锁。
/** * Created by malei on 2017/10/25. */ public class Test { private static int i = 0; private static Object obj1 = new Object(); private static boolean flag = false; public static void main(String[] args) { Thread t1 = new Thread(new Test().new myRunn1(), "狗先"); t1.start(); Thread t2 = new Thread(new Test().new myRunn2(), "猫先"); t2.start(); } class myRunn1 implements Runnable { public void run() { while (i < 10) { synchronized (obj1) { i++; log(i); flag = true; obj1.notify(); //这一步只是唤醒等待的线程,但是不会释放锁 try { obj1.wait(); //执行该方法马上释放锁 } catch (InterruptedException e) { e.printStackTrace(); } } } } } class myRunn2 implements Runnable { public void run() { while (i < 10) { if (flag) { synchronized (obj1) { i++; log(i); flag = false; obj1.notify(); try { obj1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } public static void log(int con) { System.out.println(Thread.currentThread().getName() + ":" + con); } }