关于线程间的通信的几个解决事例

public class MySynchronizedTest implements Runnable {//线程加锁时应是同一对象
int i=100;
Object object=new Object();
boolean flag=true;
//对方法加锁
public synchronized void count1()
{
while(flag){
try {//睡眠200ms
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(this.i>0)
{
System.out.println(Thread.currentThread().getName()+"在执行。。。");
i--;
System.out.println("i="+i);
}
else{
flag=false;
}
}

}
public void run() {
//count1();
while(flag){
try {//睡眠200ms
Thread.sleep(1/2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (object) {
if(this.i>0)
{System.out.println(Thread.currentThread().getName()+"在执行。。。");
i--;
System.out.println("i="+i);
}

}


}

}
}

上述做了个简单的加锁方式的事例

public void print(int i)
{synchronized (this) {//如果为this和print3同步,如果为this.getClass就和3同步
System.out.println(Thread.currentThread().getName()+"正在执行。。");
System.out.println(i);
}

}
//和该对象的全局变量互斥,比如this。getclass
public static synchronized void print2(int i)
{
System.out.println(Thread.currentThread().getName()+"正在执行。。");
System.out.println(i);
}
public synchronized void print3(int i)
{
System.out.println(Thread.currentThread().getName()+"正在执行。。");
System.out.println(i);
}

}

方法模块间的线程同步

public class MyMainThreadCommunication {

/**
* @param args
*/
public static void main(String[] args) {
Thread thread=new Thread(new MyThrad());
/*for(int i=0;i<10;i++)
{
thread.start();

}
*/
for(int j=0;j<10;j++){
new Thread(new MyThrad()).start();
synchronized (MyMainThreadCommunication.class) {


for(int i=0;i<10;i++)
{
System.out.println(i+"主线程正在执行。。。。。。。");

}
}
}

}

}

public class MyThrad implements Runnable{

public void run() {
//和MyMainThreadCommunication.class的main中的主线程互斥
synchronized(MyMainThreadCommunication.class) {
for(int i=0;i<15;i++)
{
System.out.println(i+"子线程正在执行。。");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("唤醒");
}

}

}

}

上述关于非同一个对象的所产生的线程实现同步

关于守护线程,守护线程是一个服务型线程,在没有其它线程时,守护线程自动退出!!!!!!

原文地址:https://www.cnblogs.com/mengziHEHE/p/3222001.html