如何避免此代码中的竞争条件? [英] How to avoid race condition from this code?

查看:115
本文介绍了如何避免此代码中的竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个线程,一个线程用于输入检查奇数或偶数,另一个用于输入字符串输入如何避免竞争条件.....提前谢谢



我尝试了什么:



there are two threads one thread is for taking input to check odd or even number and the other is for taking string input how to avoid race condition..... thank you in advance

What I have tried:

import java.util.Scanner;
class Palindrome implements Runnable
{
	Thread t;
	Palindrome()
	{
		t=new Thread(this,"Palindrome");
		t.start();
	}
	
	public void run()
	{
		PalindromeTest();
	}
	synchronized void PalindromeTest()
	{
		
			Scanner sc=new Scanner(System.in);
			System.out.println("Enter a string to check pallindrome : ");
			String s=sc.nextLine();
			String rev="";
			
			int size=s.length()-1;
			for(int i=0;i<=size;i++)
			{
				rev=rev + s.charAt(size-i);
			}
			if(rev.equalsIgnoreCase(s))
				System.out.println("The string is Pallindrome");
			else
				System.out.println("The string is not palindrome");
			notify();

	}
}

class OddEven implements Runnable
{
	Thread t;
	OddEven()
	{
		t=new Thread(this,"Palindrome");

		t.start();
	}
	
	public void run()
	{
		try
		{
			t.wait();
			OddEvenTest();
		}
		catch(InterruptedException e)
		{
			System.out.println(e);
		}
		
	}
	void OddEvenTest()
	{
			if(t.wait())
			{
				t.suspend();
			}
			Scanner sc=new Scanner(System.in);
			System.out.println("Enter a number to check odd or even : ");
			int s=sc.nextInt();
			if(s%2==0)
				System.out.println("The number "+s+ " is even");
			else
				System.out.println("The number "+s+ " is odd");

	}
}

class TestThread
{
	public static void main(String args[])
	{
		new Palindrome();
		new OddEven();
	}
}

推荐答案

引用:

有两个线程,一个线程用于输入检查奇数或偶数,另一个是用于输入字符串输入如何避免竞争条件.....提前谢谢

there are two threads one thread is for taking input to check odd or even number and the other is for taking string input how to avoid race condition..... thank you in advance

你的陈述根据定义是竞争条件,因为2个线程正在接受输入,每个输入只能被接受一次。



没有解决方案。



所有你能做的就是详细解释你想做什么(不谈论线程)。

Your statement is a race condition by definition because 2 threads are taking input and each input can be taken only once.

There is no solution to this.

All you can do is to explain in details what you want to do (without talking about threads).


这篇关于如何避免此代码中的竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆