Caso de operación clásica entre hilos-productor y caso de consumidor
Modelo de programa básico:
package Project.Study.Multithreading;
class Message{
private String title; //保存信息的标题
private String content; //保存信息的内容
public void setTitle(String title) {
this.title = title;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
}
class Producer implements Runnable{ //定义生产者
private Message msg=null;
public Producer(Message msg){
this.msg=msg;
}
@Override
public void run(){
for (int x=0;x<50;x++){ //生产50次数据
if(x%2==0){
this.msg.setTitle("小关"); //定义title属性
try {
Thread.sleep(100); //延迟操作
}catch (InterruptedException e){
e.printStackTrace();
}
this.msg.setContent("学习Java");//设置content属性
}else{
this.msg.setTitle("小梁"); //设置title属性
try {
Thread.sleep(100); //延迟操作
}catch (InterruptedException e){
e.printStackTrace();
}
this.msg.setContent("学习python");//设置content属性
}
}
}
}
class Consumer implements Runnable{
private Message msg;
public Consumer(Message msg){
this.msg=msg;
}
@Override
public void run(){
for(int x=0;x<50;x++){
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(this.msg.getTitle()+"-->"+this.msg.getContent());
}
}
}
public class Test10 {
public static void main(String []args){
Message msg=new Message();
new Thread(new Producer(msg)).start();
new Thread(new Consumer(msg)).start();
}
}
//结果:
//小梁-->学习Java
//小关-->学习python
//小梁-->学习Java
//小关-->学习python
//小梁-->学习Java
//小关-->学习python
//小梁-->学习Java
//小关-->学习python
//小梁-->学习Java
//(...)
Originalmente, el resultado esperado del programa es: Xiaoguan-> learning Java, Xiaoliang-> learning python,
pero obviamente hay un problema, los datos configurados están desalineados, los datos se extraen y configuran repetidamente.
Resolver el problema del desorden de datos
La desalineación de los datos se debe completamente a operaciones asincrónicas, por lo que se debe utilizar el procesamiento sincrónico.
Ejemplo: únete a la sincronización para resolver el problema del desorden de datos
package Project.Study.Multithreading;
class Message2{
private String title; //保存信息的标题
private String content; //保存信息的内容
public synchronized void set(String title,String content){
this.title=title;
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
this.content=content;
}
public synchronized void get(){
try{
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(this.title+"-->"+this.content);
}
}
class Producer2 implements Runnable{
private Message2 meg=null;
public Producer2(Message2 msg){
this.meg=msg;
}
@Override
public void run(){
for(int x=0;x<20;x++){
if(x%2==0){
this.meg.set("小关","学习Java");
}else{
this.meg.set("小梁","学习Python");
}
}
}
}
class Consumer2 implements Runnable{
private Message2 msg=null;
public Consumer2(Message2 msg){
this.msg=msg;
}
@Override
public void run(){
for (int x=0;x<20;x++){
this.msg.get();
}
}
}
public class Test11 {
public static void main(String []args)throws Exception{
Message2 msg=new Message2();
new Thread(new Producer2(msg)).start();
new Thread(new Consumer2(msg)).start();
}
}
//结果:
//小梁-->学习Python
//小梁-->学习Python
//小梁-->学习Python
//小梁-->学习Python
//(...)
El procedimiento anterior resuelve el problema de la desalineación de datos, pero todavía hay problemas de eliminación y configuración repetidas.
Resolver duplicación de datos
Soporte de clase de objeto para subprocesos múltiples
No. | Método | Tipo | Descripción |
---|---|---|---|
1 | public final void wait () arroja InterruptedException | Ordinario | Hilo esperando |
2 | público final nulo notificar () | Ordinario | Despierta el primer hilo de espera |
3 | público final nulo notifyAll () | Ordinario | Despierta todos los hilos en espera |
En general, todos los hilos de espera se organizarán en orden.
Si se usa el
método notify () , se despertará el primer subproceso en espera; si se usa el método notifyAll (), se despertarán todos los subprocesos en espera . El subproceso que tenga la mayor prioridad se ejecutará primero.
Ejemplo:
package Project.Study.Multithreading;
class Message3{
private String title;
private String content;
private boolean flag=true;
//flag==true:表示可以生产,但是不能拿走
//flag==false:表示可以取走,但是不能生产
public synchronized void set(String title,String content){
if(this.flag==false){
try {
super.wait(); //等待
}catch (InterruptedException e){
e.printStackTrace();
}
}
this.title=title;
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
this.content=content;
this.flag=false; //已经生产完成,修改标志位
super.notify(); //唤醒等待线程
}
public synchronized void get(){
if (this.flag==true){ //未生产,不能取走
try {
super.wait(); //等待
}catch (InterruptedException e){
e.printStackTrace();
}
}
try {
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(this.title+"-->"+this.content);
this.flag=true; //已经取走了,可以继续生产
super.notify(); //唤醒等待线程
}
}
class Producer3 implements Runnable{
private Message3 meg;
public Producer3(Message3 msg){
this.meg=msg;
}
@Override
public void run(){
for(int x=0;x<10;x++){
if(x%2==0){
this.meg.set("小关","学习Java");
}else{
this.meg.set("小梁","学习Python");
}
}
}
}
class Consumer3 implements Runnable{
private Message3 msg;
public Consumer3(Message3 msg){
this.msg=msg;
}
@Override
public void run(){
for (int x=0;x<10;x++){
this.msg.get();
}
}
}
public class Test12 {
public static void main(String []args){
Message3 msg=new Message3();
new Thread(new Producer3(msg)).start();
new Thread(new Consumer3(msg)).start();
}
}
//结果:
//小关-->学习Java
//小梁-->学习Python
//小关-->学习Java
//小梁-->学习Python
//小关-->学习Java
//小梁-->学习Python
//小关-->学习Java
//小梁-->学习Python
//小关-->学习Java
//小梁-->学习Python
El procedimiento anterior resuelve los problemas de desalineación de datos, eliminación repetida de datos y configuración repetida.
Sugerencia:
La diferencia entre sleep () y wait ():
1.sleep () es un método estático definido por la clase Thread, lo que significa que el thread duerme y dará la oportunidad de ejecución a otros hilos, pero el estado de monitoreo aún se mantiene y se reanudará automáticamente;
2.wait ( ) Es un método definido por la clase Object, lo que significa que el hilo espera hasta que se ejecute notify () o notifyAll ().