线程之间是怎么通讯的呢?
线程之间的通信是多个线程操作同一个资源
代码:
package tread;
class Res{
String name;
String sex;
}
class input implements Runnable
{ private Res r;
input(Res r){
this.r=r;
}
public void run() {
int x=0;
while(true) {
if(x==0) {
r.name="李四";
r.sex="男";
}
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() {
System.out.println(r.name+"...."+r.sex);
}
}
public class xxxx {
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();
}
}
输出:刘梅梅....男
这样会出错的,咱们要怎么解决呢?需要同步:
气死我了上代码:
package tread;
class Res{
String name;
String sex;
}
class input implements Runnable
{ private Res r;
input(Res r){
this.r=r;
}
public void run() {
int x=0;
while(true) {
synchronized(input.class) {
if(x==0) {
r.name="李四";
r.sex="男";
}
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() {
synchronized(input.class) {
System.out.println(r.name+"...."+r.sex);
}
}
}
public class xxxx {
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();
}
}
输出:李四....男
加了同步以后,会好很多,注意output和input都要同步。
用wait()和noyify()方法实现线程的唤醒机制。
package tread;
class Res{
String name;
String sex;
boolean flag=false;
}
class input implements Runnable
{ private Res r;
input(Res r){
this.r=r;
}
public void run() {
int x=0;
while(true) {
if(r.flag)
try {
r.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(input.class) {
if(x==0) {
r.name="李四";
r.sex="男";
}
else {
r.name="刘梅梅";
r.sex="女";
}
x=(x+1)%2;
r.notify();
}}
}
}
class output implements Runnable
{ private Res r;
output(Res r){
this.r=r;
}
public void run() {
synchronized(input.class) {
System.out.println(r.name+"...."+r.sex);
}
}
}
public class xxxx {
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();
}
}
输出:
李四....男
刘梅梅....女
李四....男
刘梅梅....女
这样会两边交叉进行。
守护线程:在非守护线程运行完成的时候,守护线程也关闭。
t1.setDaemon(true);
t1.start();
在代码块中这样写了start()函数前面
join()方法,设置了join方法的线程,主线程会等这个线程去执行完成再去结束。
t1.join();
t1.start();