黑马程序员技术交流社区
标题:
刚学多线程,调了会程序终于运行成功了,庆祝一下
[打印本页]
作者:
紫夜灵魂
时间:
2015-7-17 15:09
标题:
刚学多线程,调了会程序终于运行成功了,庆祝一下
这次弄得是线程间通信的问题。
里面有个什么等待\唤醒机制。哦哦
用东西是有条件的,
必这须得在同步里使用,因为使用到的方法是对线程进行的操作,是锁调用这些方法。
一定要明确是哪个锁的线程。
下面是看完米老爷视频打的代码,期间还出过错,不过总算是调好了
package com.itheima.Thread;
/**
* 线程间间通信演示事例
*
* 多个线程操作相同的资源,但是线程的任务是不同的。
*
* 解决安全问题,线程需要加锁而且需要加通一把锁
* @author DELL
*
* 等待/唤醒机制
* 必须在同步中使用,因为这些方法都是锁的方法,都是用来操作线程状态的。
* 必须要明确是哪个锁
*
*/
public class CommnicateDemo {
public static void main(String[] args) {
Resource r = new Resource();//只实例化一个资源,供给多个线程共享
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
/**
* 多个线程处理的资源
*/
class Resource{
private String name;
private String sex;
boolean flag = false;
public synchronized void set(String name,String sex){
if(this.flag){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.name= name;
this.sex = sex;
this.flag = true;//本线程再执行会被冻结
this.notify();//唤醒其他线程
}
public synchronized void out(){
if(!this.flag){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println(this.name+"-----------------"+this.sex);
this.flag = false;
this.notify();
}
}
/**
* 负责写入信息的线程
* @author DELL
*
*/
class Input implements Runnable{
private Resource r;
Input(Resource r){//传入线程共用资源
this.r = r;
}
public void run(){
int x = 0;
while(true){
synchronized(r){
if(x % 2 == 0){
this.r.set("zhansan","nan");
}else{
this.r.set("丽丽","女女女女女女呢");
}
}
x++;
}
}
}
/**
* 负责打印信息的线程
* @author DELL
*
*/
class Output implements Runnable{
private Resource r;
Output(Resource r){
this.r = r;
}
public void run(){
while(true){
this.r.out();
}
}
}
复制代码
不容易呀,大家觉得多线程这东东要怎么学啊。什么项目里会用到多线程啊,不知道要在哪里使用。
作者:
野驴少东
时间:
2015-7-17 15:25
我觉的这多线程就像个厕所,用到公用的内容的时候就用到它
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2